Home > Software design >  Find duplicates for a list of objects in c#
Find duplicates for a list of objects in c#

Time:11-15

If a list has 2 or more rows, can we compare the values of rows against that list to check if they are matching with any other inorder to merge them if found any

I have below list which has 2 records. Need to check if values of column 1,column 2 are same.if so need to add the Value column in inner list.

{
List: [
{
Amount :[{Value : 10}],
Column1: "Objective 1",
Column2: "6789"
},{
Amount :[{Value : 10}],
Column1: "Objective 1",
Column2: "6789"
}]}

I have fetched the distinct values in list and compared with the actual list to add. But that's not working

Tried using distinct(). It gives only the distinct rows but need to merge the values if duplicate found

I must have output as single row with value as 20

{
List: [
{
 Amount :[{Value : 20}],
Column1: "Objective 1",
Column2: "6789"
}]}

CodePudding user response:

Assuming you have something like this:

var list = new List<MyClass>
{
    new MyClass
    {
        Column1 = "Objective 1",
        Column2 = "6789" ,
        Amount = new List<Amount> 
        {
            new Amount { Value = 10 }
        }
    },
    new MyClass
    {
        Column1 = "Objective 1",
        Column2 = "6789" ,
        Amount = new List<Amount>
        {
            new Amount { Value = 10 }
        }
    }
};

...you can group the list by the identifying properties (e.g. Column1 and Column2) and select new instances where the amount value is a sum of all the amount values in the group:

var result = list
    .GroupBy(x => new { x.Column1, x.Column2 })
    .Select(grp => new MyClass
    {
        Column1 = grp.Key.Column1,
        Column2 = grp.Key.Column2,
        Amount = new List<Amount>
        {
            new Amount
            {
                Value = grp.SelectMany(x => x.Amount).Sum(x => x.Value)
            }
        }
    }).ToList();
  • Related