我必须将两个字典合并到一个字典中,删除重复的条目,并添加(如果第一个字典中不存在)。
Dictionary<int, string> firstDict = new Dictionary<int, string>();
firstDict.Add(1, "X");
firstDict.Add(2, "B");
Dictionary<int, string> secondDict = new Dictionary<int, string>();
secondDict.Add(1, "M");
secondDict.Add(4, "A");
Run Code Online (Sandbox Code Playgroud)
结果应该是这样的:
{4, "A"}
{2, "B"}
{1, "X"}
Run Code Online (Sandbox Code Playgroud)
您可以将 Concat 与示例 LINQ 结合使用来实现您想要的目的。这里是:
Dictionary<int, string> result =
firstDict.Concat(secondDict.Where(kvp => !firstDict.ContainsKey(kvp.Key)))
.OrderBy(c=>c.Value)
.ToDictionary(c => c.Key, c => c.Value);
Run Code Online (Sandbox Code Playgroud)
结果是:
{4, "A"}
{2, "B"}
{1, "X"}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4479 次 |
| 最近记录: |