Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach with a where clause?

Tags:

c#

foreach

where

Is there such a structure in C# where I could say something similar to the following:

foreach(object obj in listofObjects where obj.property == false){

so that it would only iterate through a specific subset of objects in the collection?

like image 273
MetalPhoenix Avatar asked Nov 28 '22 01:11

MetalPhoenix


2 Answers

It's simple with extension mehtods:

foreach(object obj in listofObjects.Where(w => !w.property))
like image 166
Vsevolod Goloviznin Avatar answered Dec 10 '22 01:12

Vsevolod Goloviznin


You can use the method syntax

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

It is also possible using the query syntax but it's not readable (to me at least):

foreach(object obj in (from x in listofObjects where !x.property select x))

If you are gonna use that I would store the query into a variable:

var query = (from x in listofObjects 
             where !x.property  
             select x);

foreach(var obj in query) { }
like image 44
Selman Genç Avatar answered Dec 10 '22 00:12

Selman Genç