我想询问是否可以将嵌套的foreach循环转换为LINQ表达式。
OCSPVerifier ocspVerifier = new OCSPVerifier(null, null);
IOcspClient ocspClient = new OcspClientBouncyCastle(ocspVerifier);
答案 0 :(得分:4)
这应该有效:
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);
答案 1 :(得分:1)
你可以做到这一点,但到目前为止你的效率并不高:
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));
答案 2 :(得分:1)
使用方法语法,您将使用此查询:
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);
答案 3 :(得分:0)
我不确定你想要走多远,但这是Linq声明做同样的事情:
listA.ForEach(a => listB.ForEach(b =>
{
if (b.IsCorrect(a)) b.DoSomething(a);
}));