This question is a slightly modified version of Convert List<T> to Dictionary with strategy
I have List < DTO > where DTO class looks like this,
private class DTO
{
public string Name { get; set; }
public int Count { get; set; }
}
I create objects and add it to List.
var dto1 = new DTO { Name = "test", Count = 2 };
var dto2 = new DTO { Name = "test", Count = 3 };
var dtoCollection = new List<DTO> {dto1, dto2};
Now my requirement is I need to create a List from the dtoCollection where Name field should be unique across the entire List.
For example, if you convert the above dtoCollection to the required List from, the resultant list should be like:
List < DTO > count should be 1;
The object inside the list should be a single DTO with Name as "test" and Count as 5
Where Count is obtained from summing up the Count fields in all DTO's whose Name fields are same
Try:
var result = dtoCollection.GroupBy(dto => dto.Name)
.Select(group => new DTO
{
Name = group.Key,
Count = group.Sum(dto => dto.Count)
})
.ToList();
This works by grouping the DTOs by name, and then from each group extracting a new DTO named from the group's key and count set to the sum of its members' counts.
var newList = dtoCollection.GroupBy(d => d.Name)
.Select(g => new DTO(){ Name=g.Key, Count=g.Select(d => d.Count).Sum()})
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With