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


source to share


5 answers


It's simple with the mehtods extension:



foreach(object obj in listofObjects.Where(w => !w.property))

      

+8


source


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


source


LINQ:

foreach( var obj in listofObjects.Where( q => q.property == false ) )
    ...

      

+3


source


You can do the following:

foreach (var obj in listOfObjects.Where(o => !o.Property))
{
    // ...
}

      

+2


source


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


source







All Articles