Rhendar
Rhendar

Reputation: 450

Add two objects in the same list

I have a list of objects. Each object contains an ID and a value. There are several objects which have the same ID but different values. How would I go about adding the values together based on the matching ID? Additionally, how would I go about removing one entry after the addition is complete?

The object in question:

public class MyObject
{
    public int ID { get; set; }
    public int Value { get; set; }
}

Below is where I am getting the duplicate objects from a list of all objects. I'm simply getting all the duplicate IDs into a list of strings and then grabbing the entire duplicate object in the duplicateObjects list.

List<MyObject> myObjects = GetMyObjectsList();
List<string> duplicateIds = myObjects.GroupBy(x => x.ID)
                                                .Where(group => group.Count() > 1)
                                                .Select(group => group.Key).ToList();

List<MyObject> duplicateObjects = myObjects.Where(x => duplicateIds.Contains(x.ID)).ToList();

I'm stuck on the last steps which are adding the duplicate values and then removing one of the duplicates. How would I accomplish this with Linq?

Upvotes: 0

Views: 1214

Answers (2)

Anu Viswan
Anu Viswan

Reputation: 18155

I hope I understood your question correctly.As clarified in the comment,you want to "sum" all the values grouped by ID and then remove one of the duplicates. Please verify if the following is how you could like it to be behave.

var duplicates = myObjects.GroupBy(x => x.ID)
                          .Select(group => new { Group = group.Count() > 1 ? group.ToList().Take(group.Count()-1) : group.ToList(),Sum=group.Count()});

For Input

enter image description here

Output

enter image description here

If you need to exclude non-duplicates, then you would need to include an additional Where Condition

var duplicates = myObjects.GroupBy(x => x.ID)
                          .Where(x=>x.Count()>1)
                          .Select(group => new { Group = group.Count() > 1 ? group.ToList().Take(group.Count()-1) : group.ToList(),Sum=group.Count()});

Upvotes: 1

Saif
Saif

Reputation: 2679

Assume the list look like this

    var list  =  new MyObject[]
    {
        new MyObject {ID = 1, Value = 2},
        new MyObject {ID = 2, Value = 2},
        new MyObject {ID = 1, Value = 3},
        new MyObject {ID = 4, Value = 4},
        new MyObject {ID = 2, Value = 4},
    };

Then just select from list group by ID and sum value like this

var result  = (from tm in list
                   group  tm by tm.ID into Test 
                   select  new 
                   {
                       ID =  Test.Key,
                       Value  =  Test.Sum(x => x.Value)
                   });

Output

ID = 1,  Value = 5
ID = 2,  Value = 6
ID = 4,  Value = 4

working fiddle here

Upvotes: 1

Related Questions