Foreach to Linq

Converts a foreach loop into an appropriate Linq query.

Availability

Available from the context menu or via shortcuts:

  • when the caret is on a foreach keyword.

Example

private string GetLongString(List<string> myStrings)
{
    string result = String.Empty;foreach(string str in myStrings)
        if(str.Length > 50) {
            result = String.Format(".{0}", str);
            break;
        }
    return result;
}

Result:

private string GetLongString(List<string> myStrings)
{
    string result = (from str in myStrings
                     where str.Length > 50
                     select String.Format(".{0}", str)).FirstOrDefault();
    return result;
}