[英]How to convert the foreach loop to linq
碼:
foreach (var item in testItems.Distinct())
{
if (!testMap.ContainsKey(item.GetId()))
{
testMap.Add(item.GetId(), item);
}
}
如何將上述代碼的foreach循環轉換為linq? 謝謝。
有時“將{x}轉換為LINQ”的正確方法是:不這樣做。 它不是適用於所有工作的工具。 您當前具有foreach
和dictionary突變的代碼就可以了。 收下。
如果重復的id(在Distinct()
)不是問題,則可以執行以下操作:
var map = testItems.Distinct().ToDictionary(x => x.GetId());
就是這樣。
testItems.ToList().ForEach(item=>
{
if (!testMap.ContainsKey(item.GetId()))
{
testMap.Add(item.GetId(), item);
}
});
對於1行版本,您可以嘗試以下操作:
testItems.Distinct().Where(i => !testMap.ContainsKey(i.GetId()).ForEach(f => testMap.Add(f.GetId, f));
盡管我不願意一次完成所有操作,但這樣做並不容易,因此我將不願意一次完成所有操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.