Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplifying linq when filtering data

Tags:

c#

.net

linq

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 :)

like image 627
Anelook Avatar asked Mar 23 '23 17:03

Anelook


2 Answers

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.

like image 83
Reed Copsey Avatar answered Apr 05 '23 23:04

Reed Copsey


var filtered = bigList.GroupBy(c=>c.Id)
                      .Select(g=> {
                                    var f = g.First();
                                    f.Count = g.Sum(c=>c.Count);
                                    return f;
                                  });
like image 44
King King Avatar answered Apr 05 '23 23:04

King King