LINQ equivalent of foreach for IEnumerable

后端 未结 22 2561
夕颜
夕颜 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:43

    ForEach can also be Chained, just put back to the pileline after the action. remain fluent


    Employees.ForEach(e=>e.Act_A)
             .ForEach(e=>e.Act_B)
             .ForEach(e=>e.Act_C);
    
    Orders  //just for demo
        .ForEach(o=> o.EmailBuyer() )
        .ForEach(o=> o.ProcessBilling() )
        .ForEach(o=> o.ProcessShipping());
    
    
    //conditional
    Employees
        .ForEach(e=> {  if(e.Salary<1000) e.Raise(0.10);})
        .ForEach(e=> {  if(e.Age   >70  ) e.Retire();});
    

    An Eager version of implementation.

    public static IEnumerable ForEach(this IEnumerable enu, Action action)
    {
        foreach (T item in enu) action(item);
        return enu; // make action Chainable/Fluent
    }
    

    Edit: a Lazy version is using yield return, like this.

    public static IEnumerable ForEachLazy(this IEnumerable enu, Action action)
    {
        foreach (var item in enu)
        {
            action(item);
            yield return item;
        }
    }
    

    The Lazy version NEEDs to be materialized, ToList() for example, otherwise, nothing happens. see below great comments from ToolmakerSteve.

    IQueryable query = Products.Where(...);
    query.ForEachLazy(t => t.Price = t.Price + 1.00)
        .ToList(); //without this line, below SubmitChanges() does nothing.
    SubmitChanges();
    

    I keep both ForEach() and ForEachLazy() in my library.

提交回复
热议问题