Anelook
Anelook

Reputation: 1277

Simplifying linq when filtering data

I wanted to ask for suggestions how I can simplify the foreach block below. I tried to make it all in one linq statement, but I couldn't figure out how to manipulate "count" values inside the query.

More details about what I'm trying to achieve: - I have a huge list with potential duplicates, where Id's are repeated, but property "Count" is different numbers - I want to get rid of duplicates, but still not to loose those "Count" values - so for the items with the same Id I summ up the "Count" properties

Still, the current code doesn't look pretty:

var grouped = bigList.GroupBy(c => c.Id).ToList();
foreach (var items in grouped)
{
    var count = 0;
    items.Each(c=> count += c.Count);
    items.First().Count = count;
}
var filtered =  grouped.Select(y => y.First());

I don't expect the whole solution, pieces of ideas will be also highly appreciated :)

Upvotes: 4

Views: 116

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564433

Given that you're mutating the collection, I would personally just make a new "item" with the count:

var results = bigList.GroupBy(c => c.Id)
                     .Select(g => new Item(g.Key, g.Sum(i => i.Count)))
                     .ToList();

This performs a simple mapping from the original to a new collection of Item instances, with the proper Id and Count values.

Upvotes: 5

King King
King King

Reputation: 63327

var filtered = bigList.GroupBy(c=>c.Id)
                      .Select(g=> {
                                    var f = g.First();
                                    f.Count = g.Sum(c=>c.Count);
                                    return f;
                                  });

Upvotes: 2

Related Questions