Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach loop with a where clause

Tags:

c#

.net

foreach

I was wondering if it's possible to create a foreach loop in C# with a where loop. Not with a if statement inside, but and where clause in the declaring of the loop.

Maybe something like this?

foreach(var n in people where n.sex == male)
{
}
like image 741
Michael Tot Korsgaard Avatar asked Aug 20 '14 18:08

Michael Tot Korsgaard


3 Answers

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))
{
}
like image 27
Dave Avatar answered Nov 02 '22 05:11

Dave


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) 
like image 144
Yuval Itzchakov Avatar answered Nov 02 '22 03:11

Yuval Itzchakov


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#.

like image 6
Eric Lippert Avatar answered Nov 02 '22 05:11

Eric Lippert