我有下面的字典:
Dictionary<string, string> test = new Dictionary<string, string>();
test.Add("1|1", "blue");
test.Add("1|2", "Nice");
test.Add("1|3", "Jaish");
test.Add("2|2", "Muna");
test.Add("3|1", "haha");
test.Add("3|2", "green");
test.Add("4|1", "red");
Dictionary<string, string> test2 = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> entry in test)
{
if (!test2.ContainsValue(entry.Key))
test2.Add(entry.Key, entry.Key);
}
Run Code Online (Sandbox Code Playgroud)
我想删除以下重复值:
test.Add("1|2", "Nice");
test.Add("1|3", "Jaish");
test.Add("3|2", "green")
Run Code Online (Sandbox Code Playgroud)
因此,删除重复项后,Dictionary密钥计数应为4.
假设通过管道分割字符串的第一部分定义了重复项:
var uniques = test.GroupBy(kv => kv.Key.Split('|')[0])
.Select(g => g.First())
.ToDictionary(kv => kv.Key, kv => kv.Value);
Run Code Online (Sandbox Code Playgroud)
这将始终选择每个组的第一个键值对.