Home > other >  Duplicates for list of objects and aggregate in C#
Duplicates for list of objects and aggregate in C#

Time:11-15

I have a list of 3 rows, comparing them with each other on certain condition to check if they match with any. If they match, need to aggregate the sum of inner list.

Below is the list I have. Need to check if the values of Property1, Property2 and Property3 (which is in InnerList) are same. If same, need to add the Percentage Column in inner list for the particular Property3 value

{
List:[
{
Property1: "Apple",
Property2: "Fruit",
    InnerList:[{Property3 : 100,Percentage: 50.00}]
},
{
Property1: "Apple",
Property2: "Fruit",
    InnerList:[{Property3 : 100,Percentage: 50.00},
               {Property3 : 50,Percentage: 50.00}]
},
{
Property1: "Mango",
Property2: "Fruit",
    InnerList:[{Property3 : 75,Percentage: 50.00}]
}
]}

Tried using Distinct() which didn't work. and also tried the below query which is used to add values for Property3 but not sure how to add condition to inner list and get the below result.

Query used:

var result = list
.GroupBy(x=> new {x.Property1,x.Property2})
.Select(grp => new Class
{
Property1 = grp.Key.Property1,
Property2 = grp.Key.Property2,
innerList = new List<InnerList>
{
new InnerList
{
   Percentage = grp.SelectMany(x=> x.innerList).Sum(x=>x.Percentage)
}
}
}).ToList();

{
List:[
{
Property1: "Apple",
Property2: "Fruit",
    InnerList:[{Property3 : 100,Percentage: 100.00},
               {Property3 : 50,Percentage: 50.00}]
},
{
Property1: "Mango",
Property2: "Fruit",
    InnerList:[{Property3 : 75,Percentage: 50.00}]
}
]}

CodePudding user response:

You can use GroupBy to group by Property1 and Property2 and then use SelectMany to flatten the inner lists. Then you can use GroupBy again to group by Property3 and sum the Percentage values.

var result = list
    .GroupBy(x => new { x.Property1, x.Property2 })
    .Select(g => new
    {
        g.Key.Property1,
        g.Key.Property2,
        InnerList = g.SelectMany(x => x.InnerList)
            .GroupBy(x => x.Property3)
            .Select(g2 => new InnerList
            {
                Property3 = g2.Key,
                Percentage = g2.Sum(x => x.Percentage)
            })
    });
  • Related