14

我有一个字典,其中项目是(例如):

  1. “一”,4
  2. “乙”,44
  3. “再见”,56
  4. “C”,99
  5. “D”,46
  6. "6672", 0

我有一个清单:

  1. “一种”
  2. “C”
  3. “D”

我想从我的字典中删除所有键不在我列表中的元素,最后我的字典将是:

  1. “一”,4
  2. “C”,99
  3. “D”,46

我能怎么做?

4

4 回答 4

22

构造新 Dictionary 以包含列表中的元素更简单:

List<string> keysToInclude = new List<string> {"A", "B", "C"};
var newDict = myDictionary
     .Where(kvp=>keysToInclude.Contains(kvp.Key))
     .ToDictionary(kvp=>kvp.Key, kvp=>kvp.Value);

如果修改现有字典很重要(例如,它是某个类的只读属性)

var keysToRemove = myDictionary.Keys.Except(keysToInclude).ToList();

foreach (var key in keysToRemove)
     myDictionary.Remove(key);

注意 ToList() 调用 - 实现要删除的键列表很重要。如果您尝试在不实现 的情况下运行代码keysToRemove,您可能会遇到异常,说明“集合已更改”之类的内容。

于 2012-11-25T16:31:32.643 回答
8
// For efficiency with large lists, for small ones use myList below instead.  
var mySet = new HashSet<string>(myList);

// Create a new dictionary with just the keys in the set
myDictionary = myDictionary
               .Where(x => mySet.Contains(x.Key))
               .ToDictionary(x => x.Key, x => x.Value);
于 2012-11-25T16:25:18.587 回答
4
dict.Keys.Except(list).ToList()
    .ForEach(key => dict.Remove(key));
于 2012-11-25T17:24:14.367 回答
0

代码:

public static void RemoveAll<TKey, TValue>(this Dictionary<TKey, TValue> target,
                                           List<TKey> keys)
{
    var tmp = new Dictionary<TKey, TValue>();

    foreach (var key in keys)
    {
        TValue val;
        if (target.TryGetValue(key, out val))
        {
            tmp.Add(key, val);
        }
    }

    target.Clear();

    foreach (var kvp in tmp)
    {
        target.Add(kvp.Key, kvp.Value);
    }
}

例子:

var d = new Dictionary<string, int>
            {
                {"A", 4},
                {"B", 44},
                {"bye", 56},
                {"C", 99},
                {"D", 46},
                {"6672", 0}
            };

var l = new List<string> {"A", "C", "D"};

d.RemoveAll(l);

foreach (var kvp in d)
{
    Console.WriteLine(kvp.Key + ": " + kvp.Value);
}

输出:

A: 4
C: 99
D: 46
于 2012-11-25T16:25:41.760 回答