繁体   English   中英

删除特定条目(在列表中定义<string> ) 来自字典<string, int>给出严重错误 --&gt;</string,></string>

[英]Removing specific entries(defined in a List<string>) from Dictionary<string, int> gives critical error -->

我有一个 List 字符串集合。 像这样,

    public List<string> filterWords = new List<string>()
    {
            "an" ,
            "be",
            " ",
            "in",
            "the",
            "of"
            ..
        ...
        .
        . 
        ....
    };

我有一个 Dictionary<string, int> 格式的字典集合,就像这样,

    {{of, 2}},
    {{an, 4}},
    {{in, 7}},
    {{the, 8}},
    {{literate, 3}},
    {{culture, 5}},
    {{be, 5}},
    ...
    and so and so

目的是检查/查找并从上述字典条目中删除包含上一个列表中的键的条目。 即一个,是等。

到目前为止,我整理的基本代码是——

    public Dictionary<string, int> UniqueWordsDictionary(Dictionary<string, int> inputDict)
    {
        try
        {
            FilterWords flObj = new FilterWords();

            var dictionary = new Dictionary<string, int>();

            int idx = 0;

            var wordsToRemove = flObj.filterWords
                .Select(record => record.Substring(0, record.IndexOf(',')));

            foreach(string wrd in wordsToRemove)
            {
                inputDict.Remove(wrd);
            }

            dictionary = inputDict;

            return dictionary;
        }
        catch(Exception exp)
        {
            throw exp.GetBaseException();
        }
    }

逻辑可能是错误的。 异常我得到一个具有相同密钥的项目已被添加

堆栈跟踪 -

    at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) at    System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) 
    at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value) at ....

使用了 idx=0,因为我只需要字典值中的默认值 0。 逻辑似乎没问题。 这是一个非常尖锐、精确的解决方案。 任何可以满足需要的关键 lambda 表达式? 'wordsToRemove' 上的 foreach 有什么问题?

观察我发布的代码块。 有一个注释行dictionary=wordsToRemove.Select.............我尝试在那个和 foreach 循环字典中进行注释。添加。 两种情况下的错误都是相同的。

** 仔细阅读添加到代码块中的注释 Thx。

如果你想删除,让我们Remove

  List<string> filterWords = ...

  // I have a dictionary collection in format of Dictionary<string, int>, Like so
  Dictionary<string, int> dictionary = ...

 ... 

  // then we Remove each word in wordsToRemove from dictionary
  foreach (string word in filterWords)
    dictionary.Remove(word);  

暂无
暂无

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

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