簡體   English   中英

如何將帶條件的嵌套foreach循環轉換為LINQ

[英]How to convert nested foreach loops with conditions to LINQ

我想問一下是否可以將下面的嵌套foreach循環轉換為LINQ表達式。

public interface IFoo
{
  bool IsCorrect(IFoo foo);
  void DoSomething(IFoo foo);
}

List<IFoo> listA; //assume that contains items
List<IFoo> listB; //assume that contains items


foreach (var a in listA)
{
  foreach (var b in listB)
  {
    if (b.IsCorrect(a))
    {
      b.DoSomething(a);
    }
  }
}

這應該工作:

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);

您可以執行此操作,但是到目前為止,這並不高效:

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));

為了避免調用ToList ,可以實現如下擴展方法:

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

然后您的查詢將是:

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));

使用方法語法,您將使用以下查詢:

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);

我不確定您要走多遠,但這是一條Linq語句,可以完成相同的操作:

listA.ForEach(a => listB.ForEach(b =>
{
    if (b.IsCorrect(a)) b.DoSomething(a);
}));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM