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?
It's simple with extension mehtods:
foreach(object obj in listofObjects.Where(w => !w.property))
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) { }
where
inside the foreach
.
Where
. It will stop exactly at !x.property
for each element on it.
Dec 29, 2014 at 19:52
You can do like this:
foreach (var obj in listOfObjects.Where(o => !o.Property))
{
// ...
}
You can use the Where
extension method and a lambda. from Linq.
Ensure you have the System.Linq
namespace referenced.
foreach (var obj in listOfObjects.Where(obj => obj.property == false))