Can all 'for' loops be replaced with a LINQ statement?

前端 未结 7 544
逝去的感伤
逝去的感伤 2021-02-05 08:48

Is it possible to write the following \'foreach\' as a LINQ statement, and I guess the more general question can any for loop be replaced by a LINQ statement.

I\'m not i

7条回答
  •  一生所求
    2021-02-05 08:52

    Technically, yes.

    Any foreach loop can be converted to LINQ by using a ForEach extension method,such as the one in MoreLinq.

    If you only want to use "pure" LINQ (only the built-in extension methods), you can abuse the Aggregate extension method, like this:

    foreach(type item in collection { statements }
    
    type item;
    collection.Aggregate(true, (j, itemTemp) => {
        item = itemTemp;
        statements
        return true;
    );
    

    This will correctly handle any foreach loop, even JaredPar's answer. EDIT: Unless it uses ref / out parameters, unsafe code, or yield return.
    Don't you dare use this trick in real code.


    In your specific case, you should use a string Join extension method, such as this one:

    ///Appends a list of strings to a StringBuilder, separated by a separator string.
    ///The StringBuilder to append to.
    ///The strings to append.
    ///A string to append between the strings.
    public static StringBuilder AppendJoin(this StringBuilder builder, IEnumerable strings, string separator) {
        if (builder == null) throw new ArgumentNullException("builder");
        if (strings == null) throw new ArgumentNullException("strings");
        if (separator == null) throw new ArgumentNullException("separator");
    
        bool first = true;
    
        foreach (var str in strings) {
            if (first)
                first = false;
            else
                builder.Append(separator);
    
            builder.Append(str);
        }
    
        return builder;
    }
    
    ///Combines a collection of strings into a single string.
    public static string Join(this IEnumerable strings, string separator, Func selector) { return strings.Select(selector).Join(separator); }
    ///Combines a collection of strings into a single string.
    public static string Join(this IEnumerable strings, string separator) { return new StringBuilder().AppendJoin(strings, separator).ToString(); }
    

提交回复
热议问题