代码:
foreach (var item in testItems.Distinct())
{
if (!testMap.ContainsKey(item.GetId()))
{
testMap.Add(item.GetId(), item);
}
}
如何将上述代码的foreach循环转换为linq?谢谢。
请您参考如下方法:
有时“将 {x} 转换为 LINQ”的正确方法是:不要。它不是适合所有工作的工具。您当前使用 foreach 和字典突变的代码没有问题。保留它。
如果重复的 ID(在 Distinct() 之后)不是问题,您或许可以这样做:
var map = testItems.Distinct().ToDictionary(x => x.GetId());
但仅此而已。
