Kakha Middle Or
Kakha Middle Or

Reputation: 164

Linq Task - Group List elements and do action for grouped elements with condition

Suppose I have list somelist with objects {bool someflag, int somevalue} I need to:

  1. Filter list by someflag=true;
  2. Group filtered list items by somevalue field;
  3. Filter found groups that have less than 2 elements;
  4. Change field somevalue for each element in filtered groups;

I did some trick to achieve this

somelist.FindAll(f => f.someflag)
            .GroupBy(g => g.somevalue).Where(g => g.Count() < 2).
            All(g => g.All(f => f.somevalue= -f.somevalue) == f.somevalue);

Is there more efficient and correct way? Is it better to convert list and use ForEach?

Upvotes: 0

Views: 41

Answers (1)

sebastian czubienko
sebastian czubienko

Reputation: 16

You can try this, I refactor this a little bit.

var valuesToChange = new HashSet<int>();
somelist.Where(item => item.someflag).ForEach(item => valuesToChange.Add(item.somevalue));
somelist.Where(item => valuesToChange.Contains(item.somevalue)).ForEach(item => item.somevalue = -item.somevalue);

HashSet should improve your performance, cause it cannot store the duplicated elements and the elements are not ordered. The rest of the code should be self-explanatory. If you care a lot about the performance I recommend using BenchmarkDotNet for performance results.

Basically, this code should improve the performance a little, depending on the list size.

Upvotes: 0

Related Questions