Code:
foreach (var item in testItems.Distinct())
{
if (!testMap.ContainsKey(item.GetId()))
{
testMap.Add(item.GetId(), item);
}
}
How to convert the foreach loop to linq for the above code? Thanks.
Sometimes the correct approach to "converting {x} to LINQ" is: don't. It isn't an appropriate tool for every job. Your current code with foreach
and dictionary mutation is fine as it is. Keep it.
If duplicate ids (after the Distinct()
) aren't an issue, you could perhaps do:
var map = testItems.Distinct().ToDictionary(x => x.GetId());
But that's about it.
testItems.ToList().ForEach(item=>
{
if (!testMap.ContainsKey(item.GetId()))
{
testMap.Add(item.GetId(), item);
}
});
For a 1 line version, you could try this:
testItems.Distinct().Where(i => !testMap.ContainsKey(i.GetId()).ForEach(f => testMap.Add(f.GetId, f));
That will do the whole operation in one line, although I am not a big fan of doing everything at once as it can be harder to debug.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.