Foreach with where clause?
Is there a structure like this in C # where I could say something similar to the following:
foreach(object obj in listofObjects where obj.property == false){
so that it only iterates through a specific subset of objects in the collection?
+3
MetalPhoenix
source
to share
5 answers
It's simple with the mehtods extension:
foreach(object obj in listofObjects.Where(w => !w.property))
+8
Vsevolod Goloviznin
source
to share
You can use method syntax
foreach(object obj in listofObjects.Where(obj => !obj.property))
The query syntax can also be used, but it is not readable (at least for me):
foreach(object obj in (from x in listofObjects where !x.property select x))
If you are going to use this, I would store the request in a variable:
var query = (from x in listofObjects
where !x.property
select x);
foreach(var obj in query) { }
+9
Selman Genç
source
to share
LINQ:
foreach( var obj in listofObjects.Where( q => q.property == false ) )
...
+3
Chris
source
to share
You can do the following:
foreach (var obj in listOfObjects.Where(o => !o.Property))
{
// ...
}
+2
msporek
source
to share
You can use extension method Where
and lambda. from Linq.
Make sure you have a namespace System.Linq
.
foreach (var obj in listOfObjects.Where(obj => obj.property == false))
+1
Daniel A. White
source
to share