简体   繁体   English

如何使用lambda表达式从字典中删除项目

[英]How can I Remove items from dictionary using lambda expression

I am not into LINQ solutions, 我不是LINQ解决方案,

I am using simple predicat to determine if the key should be removed, For example if the dictionary is construct like Dictionary<int, int> , so how should I remove all the entries with negative data 我使用简单的谓词来确定是否应该删除键,例如,如果字典构造像Dictionary<int, int> ,那么我应该如何删除所有带有负数据的条目

I am prefer to use the same dictionary, not to create new one, I don't have preformance issues 我更喜欢使用相同的字典,而不是创建新字典,我没有性能问题

Is there a way to do it, without using LINQ, but using Lambda expressions? 有没有办法做到这一点,不使用LINQ,而是使用Lambda表达式?

I didn't want solutions in LINQ because no one is using them in my project, didn't want to be the first.., but because I saw the LINQ solutions look better, I will use them them.. 我不想在LINQ中使用解决方案,因为没有人在我的项目中使用它们,不想成为第一个..但是因为我看到LINQ解决方案看起来更好,我将使用它们..

The simplest way is probably to create a new dictionary, if that's okay for you: 最简单的方法可能是创建一个新的字典,如果这对你没问题:

var newDictionary = oldDictionary.Where(pair => pair.Value >= 0)
                                 .ToDictionary(pair => pair.Key,
                                               pair => pair.Value);

If you have to mutate the existing dictionary (eg because several other objects have reference to the same dictionary) you'd need to build a list of keys to remove, then remove them afterwards: 如果你必须改变现有的字典(例如,因为其他几个对象引用了同一个字典),你需要构建一个要删除的键列表,然后删除它们:

var toRemove = dictionary.Where(pair => pair.Value < 0)
                         .Select(pair => pair.Key)
                         .ToList();

foreach (var key in toRemove)
{
    dictionary.Remove(key);
}

EDIT: I've just noticed the first sentence: "I am not into LINQ solutions". 编辑:我刚刚注意到第一句话:“我不是进入LINQ解决方案”。 If that means you don't want to use a LINQ solution, here's the by-hand version: 如果这意味着您不想使用 LINQ解决方案,那么这是手动版本:

List<int> toRemove = new List<int>();
foreach (KeyValuePair<int, int> pair in dictionary)
{
    if (pair.Value < 0)
    {
        toRemove.Add(pair.Key);
    }
}

foreach (var key in toRemove)
{
    dictionary.Remove(key);
}

... but if you can use LINQ, I'd encourage you do. ...但是如果你使用LINQ,我会鼓励你这样做。 My second solution is equivalent to the "by-hand" version, but more readable IMO. 我的第二个解决方案相当于“手工”版本,但更具可读性的IMO。

By merely using lambda expression: 仅使用lambda表达式:

foreach (var i in myDict.Where(d => (d.Value  < 0 || d.key <0)).ToList() ) 
{
  myDict.Remove(i.Key);
}
var toRemove = dict.Keys.Where(predicate).ToArray();
foreach (var key in toRemove) {
    dict.Remove(key);
}

Well if you add 好吧,如果你添加

namespace MMExtensions
{
    public static class DictionaryExtensions
    {
        public delegate bool Predicate<TKey, TValue>(KeyValuePair<TKey, TValue> d);

        [MethodImpl(MethodImplOptions.Synchronized)]
        public static void Filter<TKey, TValue>(
            this Dictionary<TKey, TValue> hashtable, Predicate<TKey, TValue> p)
        {
            foreach (KeyValuePair<TKey, TValue> value in hashtable.ToList().Where(value => !p(value)))
                hashtable.Remove(value.Key);
        }
    }
}

And you had some dataset as dictionary: 你有一些数据集作为字典:

    Dictionary<string, int> d =
            new Dictionary<string, int> {{"v", -3}, {"val1", 1}, {"val2", 2}};

Then you could use: 然后你可以使用:

    d.Filter(delegate(KeyValuePair<string, int> kv) { return kv.Value >= 0; });
    d.Filter(kv => kv.Value >= 0);// or as lambda

Do you want to remove the items from that dictionary, or are you happy to use a new dictionary without those items included? 是否要从该词典中删除项目,或者您是否乐意使用未包含这些项目的新词典?

var d = new Dictionary<int,int>();
var newDict = d.Where(entry => entry.Value >= 0).ToDictionary(entry => entry.Key, entry => entry.Value);

Easiest one: 最简单的一个:

Dictionary<long, long> dict...
Dictionary<long, long> result = dict.Were(x => x.Value >= 0).ToDictionary(x => x.Key, x => x.Value);

Or just loop over all in 'for' in reverse order and remove invalid ones. 或者只是以相反的顺序循环遍历'for'并删除无效的。

I know you said you are not into Linq, but I could not contain myself with the following solution, plus it is still useful if you read the title of your question. 我知道你说你没有进入Linq,但是我不能用以下解决方案来控制自己,如果你阅读了你的问题的标题,它仍然是有用的。 This is probably the most elegant solution to your problem: 这可能是您问题的最优雅解决方案:

dictionary.Where(pair => pair.Value < 0)
          .Select(pair => { 
              dictionary.Remove(pair.Key);
              return pair.Key;
          });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM