如何使用 LINQ 过滤字典并将其从同一类型返回到字典

我有以下字典:

Dictionary<int,string> dic = new Dictionary<int,string>();
dic[1] = "A";
dic[2] = "B";

我想过滤字典中的条目,并将结果重新分配给相同的变量:

dic = dic.Where (p => p.Key == 1);

如何以字典的形式从同一类型[ <int,string>]返回结果?

我试过 ToDictionary,但没用。

78123 次浏览

ToDictionary is the way to go. It does work - you were just using it incorrectly, presumably. Try this:

dic = dic.Where(p => p.Key == 1)
.ToDictionary(p => p.Key, p => p.Value);

Having said that, I assume you really want a different Where filter, as your current one will only ever find one key...