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

前端 未结 7 531
逝去的感伤
逝去的感伤 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:56

    In general, you can write a lambda expression using a delegate which represents the body of a foreach cycle, in your case something like :

    resource => { if (sb.Length != 0) sb.Append(", "); sb.Append(resource.Id); }
    

    and then simply use within a ForEach extension method. Whether this is a good idea depends on the complexity of the body, in case it's too big and complex you probably don't gain anything from it except for possible confusion ;)

提交回复
热议问题