Reputation: 164
Suppose I have list somelist with objects {bool someflag, int somevalue}
I need to:
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
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