Home > database >  Find duplicate objects based on a property and combine the values of the property
Find duplicate objects based on a property and combine the values of the property

Time:09-29

I have the following list of objects:

[
    {
        "category": "animal",    
        "example": "cat"
    },
    {
        "category": "bird",
        "example": "parrot"
    },
    {
        "category": "animal",
        "example": "dog"
    }
]

I need to find out the duplicates and output the following list:

[
    {
        "category": "animal",    
        "example": ["cat", "dog"]
    },
    {
        "category": "bird",
        "example": "parrot"
    }
]

With the following code, I'm able to find out the duplicates:

var a = inputList.GroupBy(x => x.category);
var duplicates = a.Where(item => item.Count() > 1);

How do I update the value of example in the inputList?

CodePudding user response:

I do not know how your models looks like but if it looks something like this:

public class AnimalsWithExample
{
    public AnimalsWithExample(string category, string example)
    {
        Category = category;
        Example = example;
    }
    
    public string Category { get; set; }
    public string Example { get; set; }
}

public class AnimalsGrouped
{
    public string Category { get; set; }
    public string[] Examples { get; set; }
}

then you can simply do this:

var list = new List<AnimalsWithExample>
{
    new AnimalsWithExample("animal", "cat"),
    new AnimalsWithExample("bird", "parrot"),
    new AnimalsWithExample("animal", "dog")
};

var listGrouped = list.GroupBy(x => x.Category)
    .Select(x => new AnimalsGrouped() { Category = x.Key, Examples = x.Select(y => y.Example).Distinct().ToArray() }).ToList();

CodePudding user response:

Common type for string and IEnumerable<string> is object, if you are OK with that (e.g. only JSON is needed), you can use that:

inputList.GroupBy(x => x.category).Select(grp => new 
{
   category = grp.Key,
   examples = grp.Select(i => i.example).Distinct().ToList()
})
.Select(i => new 
{
  i.category,
  example = i.examples.Count == 1 ? (object)i.examples.First() : i.examples
})
  • Related