foreach loop with a where clause

As Yuval's answer and its comments point out, you can put any query -- in either "fluent" or "query syntax" form -- as the collection expression. This leads to awkward constructions like:

foreach(var person in from person in people where person.sex == male select person) 

Not only is this very verbose, in the example I have given here the simple name person is used both in the query and the loop declaration. You might wonder why that is even legal, as normally C# is strict about ensuring that a simple name has only one meaning in a given local variable scope. The answer is here: http://ericlippert.com/2009/11/05/simple-names-are-not-so-simple-part-two/

IIRC the C# design team briefly considered a syntax such as you describe, but never got even as far as writing a specification. It's a nice idea but it just wasn't a sufficiently awesome language extension to make it to the top of the list. This would be a nice feature to pitch for a future version of C#.


Yes, it is possible:

Method Syntax:

foreach (var person in people.Where(n => n.sex == "male"))
{
}

Or the rather lengthy Query Syntax:

foreach (var person in from person in people where person.sex == "male" select person) 

It looks like what you need is a lambda expression to limit the items the foreach look works with.

Based on your limited example, something like this:

foreach(var n in people.Where(n => n.sex == male))
{
}

Tags:

C#

.Net

Foreach