Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group a List based on uniqueness

Tags:

c#

list

lambda

linq

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

like image 644
Rockstart Avatar asked Nov 14 '12 12:11

Rockstart


2 Answers

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.

like image 171
Ani Avatar answered Sep 29 '22 21:09

Ani


var newList = dtoCollection.GroupBy(d => d.Name)
             .Select(g => new DTO(){ Name=g.Key, Count=g.Select(d => d.Count).Sum()})
             .ToList();
like image 45
L.B Avatar answered Sep 29 '22 21:09

L.B