如何LINQ查询使用拉姆达表达式转换
问题描述:
我想这个LINQ代码切换到lambda表达式:如何LINQ查询使用拉姆达表达式转换
foreach (var id in orderLinesToSplit)
{
int result =
(from ol in orderLines
from splittedOl in orderLines
where ol.Key == id
&& ol.Value == splittedOl.Value
&& ol.Key != splittedOl.Key
select splittedOl.Key).FirstOrDefault();
}
的目标是获得一个对id
(从oderLinesToSplit
)和result
的Dictionary<int, int>
(来自linq查询的结果)。它可以用一个lambda表达式来完成吗?
感谢
答
var result=
(
from ol in orderLines
from splittedOl in orderLines
where orderLinesToSplit.Contains(ol.Key)
&& ol.Value == splittedOl.Value
&& ol.Key != splittedOl.Key
select new
{
splittedOl.Key,
splittedOl.Value
}
).ToDictionary (v =>v.Key,v=>v.Value);
或者,如果你真的想在一个表达。然后是这样的:
var result=
(
db.orderLines.Join
(
db.splittedOl,
ol=>ol.Value,
splittedOl=>splittedOl.Value,
(ol,splittedOl)=>new
{
olKey=ol.Key,
splittedOlKey=splittedOl.Key
}
).Where(l =>l.olKey!= l.splittedOlKey && orderLinesToSplit.Contains(l.olKey))
.ToDictionary(l =>l.olKey,v=>v.splittedOlKey)
);
其中db是LINQ数据上下文
耶的作品,但我需要的拉姆达expresion ...... – 2012-02-08 13:16:45
更新答案 – Arion 2012-02-08 14:22:15
@LauraJimenez为什么你需要它作为一个拉姆达表达?它的查询相同,只是难以阅读。 – Magnus 2012-02-08 17:21:42