pm1*_*100 0 c# linq dictionary .net-4.0
我有
IDictionary<string,object> d1;
Dictionary<string, object> d2;
Run Code Online (Sandbox Code Playgroud)
我需要从 d1 中删除 d2 中没有的所有条目。
我知道我可以用 for 循环等来做到这一点,但那是上个世纪的事了;我想把事情做好。
我必须
d1.Where(x => {return d2.ContainsKey(x.key);});
Run Code Online (Sandbox Code Playgroud)
但不知道下一步该做什么
LINQ 并不是为了修改现有元素而设计的 - 但您始终可以创建一个新字典。例如:
d1 = d1.Where(x => d2.ContainsKey(x.Key))
.ToDictionary(x => x.Key, x => x.Value);
Run Code Online (Sandbox Code Playgroud)
或者:
d1 = d1.Keys.Intersect(d2.Keys)
.ToDictionary(key => x.Key, key => d1[key]);
Run Code Online (Sandbox Code Playgroud)
正如其他人所说,如果您更热衷于进行Remove操作,我会循环。例如:
foreach (var key in d1.Keys.Except(d2.Keys).ToList())
{
d1.Remove(key);
}
Run Code Online (Sandbox Code Playgroud)
(顺便说一句,我不确定您为什么在示例代码中使用语句 lambda。)
| 归档时间: |
|
| 查看次数: |
1428 次 |
| 最近记录: |