Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactor foreach and if's to Linq

Tags:

c#

linq

Would it be possible to combine all the given code to linq, which then would return 'true' or 'false'? Or is this fine the way it is?

If it is possible, would there be a significant performance difference?(The array and list won't contain more than 100 elements)

foreach (var item in myArray)
{
    if (myList.Exists(x => x.Value == item))
    {
        amountTrue++;
    }
}

if (myArray.Count() == amountTrue)
{
    isValid = true;
}
like image 702
foxtrot2nov Avatar asked Nov 28 '22 20:11

foxtrot2nov


1 Answers

As far as I can see, the code is designed to check

if all the items of the myArray are in the myExists

the implementation:

  isValid = myArray
    .All(item => myList.Exists(x => x.Value == item));

if you want to refactor for performace as well as for readability, have a look for bottlenecks. Say, is it myList.Exists that slows down? In that case think of HashSet<T> where T is a type of x.Value etc.

like image 148
Dmitry Bychenko Avatar answered Nov 30 '22 11:11

Dmitry Bychenko