Linq simplification when filtering data

I wanted to ask how can I simplify the foreach block below. I tried to do all this in a single linq expression, but I could not figure out how to manipulate the "count" values ​​inside the query.

More on what I'm trying to achieve: - I have a huge list with potential duplicates where Id are repeated, but the "Count" property is different numbers - I want to get rid of duplicates, but still not lose these "Count" values ​​- therefore, for elements with the same identifier, I summarize the "Count" properties

However, the current code does not look very 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 do not expect the whole solution, ideas will be also highly appreciated :)

+4
source share
2 answers
 var filtered = bigList.GroupBy(c=>c.Id) .Select(g=> { var f = g.First(); f.Count = g.Sum(c=>c.Count); return f; }); 
+2
source

Given that you mutate the collection, I personally just make a new “element” with the score:

 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 corresponding Id and Count values.

+5
source

Source: https://habr.com/ru/post/1498034/


All Articles