Reputation:
I have a loop that is going through each element of a list.
At the moment I have the foreach loop, and inisde, an if that check a variable for the element of the list. If the value is true, I do certain activities, otherwise I move on.
I was wondering if there is some sort of construct, that would allow me to write something like
foreach (myclass item in itemlist) where ( item.is_red)
{
... do something
}
instead than what I have currently
foreach (myclass item in itemlist)
{
if (item.is_red)
... do something
}
From what I recall, the "where" can be used only as constant definition mechanism, like when defining a specific type of class; so it can't be used in the context that I am presenting here. Am I stuck with the if-else inside the loop as only solution?
Upvotes: 3
Views: 139
Reputation: 1543
Convert the enumeration to List
and use the Where
and ForEach
LINQ operator:
itemlist.Where(t => t.is_red).ToList().ForEach(t => DoSomething(t));
or
itemlist.Where(t => t.is_red).ToList().ForEach(t =>
{
// do something
}
Upvotes: 5
Reputation: 265231
Almost :)
foreach (var item in (from i in numbers where i.is_red select i))
{
... do something
}
There generally is a small performance hit when LINQ is used to iterate over lists or arrays, since an enumerator object is to be created.
Another way to tackle your problem is to use your condition as guard clause. This can reduce nesting and complexity and usually improves readability (although there is also the opinion of not using multiple returns/continues/breaks in a function/loop to keep cyclomatic complexity down):
foreach (var item in itemlist)
{
if (!item.is_red) { continue; }
... do something
}
In the end it probably boils down to company policy/personal preference.
Upvotes: 1
Reputation: 37808
You could use LINQ
foreach (myclass item in itemlist.Where(i => i.is_red))
{
//... do something
}
Upvotes: 3
Reputation: 30813
Yes, you could filter what you want iterate with LINQ Where
in the collection first:
foreach (myclass item in itemlist.Where(x => x.is_red)) //here is the `Where`
{
//do your stuffs
}
Upvotes: 1