LINQ equivalent of foreach for IEnumerable

后端 未结 22 2564
夕颜
夕颜 2020-11-21 22:54

I\'d like to do the equivalent of the following in LINQ, but I can\'t figure out how:

IEnumerable items = GetItems();
items.ForEach(i => i.DoS         


        
22条回答
  •  执笔经年
    2020-11-21 23:44

    You could use the FirstOrDefault() extension, which is available for IEnumerable. By returning false from the predicate, it will be run for each element but will not care that it doesn't actually find a match. This will avoid the ToList() overhead.

    IEnumerable items = GetItems();
    items.FirstOrDefault(i => { i.DoStuff(); return false; });
    

提交回复
热议问题