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

前端 未结 7 535
逝去的感伤
逝去的感伤 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条回答
  •  梦毁少年i
    2021-02-05 08:59

    The specific loop in your question can be done declaratively like this:

    var result = ListOfResources
                .Select(r => r.Id.ToString())
                .Aggregate(new StringBuilder(), (sb, s) => sb.Append(sb.Length > 0 ? ", " : String.Empty).Append(s))
                .ToString(); 
    

    As to performance, you can expect a performance drop but this is acceptable for most applications.

提交回复
热议问题