How to convert nested foreach loops with conditions to LINQ

前端 未结 4 796
小蘑菇
小蘑菇 2021-01-16 14:57

I\'d like to ask if it is possible to convert below nested foreach loops to LINQ expression.

public interface IFoo
{
  bool IsCorrect(IFoo foo);
  void DoSom         


        
相关标签:
4条回答
  • 2021-01-16 15:36

    You can do this but this is not more efficient what you have so far:

    var query= listA.SelectMany(a=>listB.Select(b=>new {a,b}))
                    .Where(e=>e.b.IsCorrect(e.a))
                    .ToList()// Foreach is a method of List<T>
                    .Foreach(e=> e.b.DoSomething(e.a));
    

    To avoid to call ToList, you can implement an extension method like this:

    public static void ForEach<T>(this System.Collection.Generic.IEnumerable<T> list, System.Action<T> action)
    {
        foreach (T item in list)
            action(item);
    }
    

    And then your query would be:

    var query= listA.SelectMany(a=>listB.Select(b=>new {a,b}))
                    .Where(e=>e.b.IsCorrect(e.a))
                    .Foreach(e=> e.b.DoSomething(e.a));
    
    0 讨论(0)
  • 2021-01-16 15:43

    With method syntax you would use this query:

    var correctPairs = listA
        .SelectMany(a => listB.Where(b => b.IsCorrect(a)).Select(b => new { a, b }));
    
    foreach (var x in correctPairs)
        x.b.DoSomething(x.a);
    
    0 讨论(0)
  • 2021-01-16 15:49

    This should work:

    var result =
        from a in listA
        from b in listB
        where b.IsCorrect(a)
        select new {a, b};
    
    foreach (var item in result)
        item.b.DoSomething(item.a);
    
    0 讨论(0)
  • 2021-01-16 15:53

    I'm not sure exactly how far you want to go with this, but this is a Linq statement doing the same thing:

    listA.ForEach(a => listB.ForEach(b =>
    {
        if (b.IsCorrect(a)) b.DoSomething(a);
    }));
    
    0 讨论(0)
提交回复
热议问题