Home > Posts > Suggestion: add optional “where” clause to “foreach” statement in C#

Suggestion: add optional “where” clause to “foreach” statement in C#

Wouldn’t it be nice if I could use in C# the following syntax?

for (SomeType repeaterVariable

      in SomeEnumerable

      where someBooleanExpressionOfRepeaterVariable)


e.g. use this one:


instead of this one:


BTW, if you wonder what FixTime does, it prepends 0: to time strings to make sure they are of format h:m:s.f

Have added this as a comment to another person’s suggestion that I see has similar format, so please vote for that one:


Categories: Posts Tags: , , , , ,
  1. 2016/05/16 at 14:55

    I guess from the above example this can be done like

    value.Count(x => x == ‘:’);

    and if its something more complex you can create your own extension similar to Count :

    public static int Count(this IEnumerable source, Func predicate);

    • 2016/05/16 at 21:43

      Thanks, that was just an example. In that specific case I don’t use Linq for performance reasons

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: