简体   繁体   中英

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

I have a List collection of strings. Like so,

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

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

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

Aim is to check/find out and remove from the above dictionary entries that contain keys from the previous list. ie an, be etcetc.

Basic code I have put together so far is --

    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();
        }
    }

The logic probably wrong. Exception I am getting An item with the same key has already been added .

The stack trace -

    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 been used, because I simply need a default value of 0 in the values of the dictionary. Logic seemed ok. What's a very sharp, precise solution for this. Any critical lambda expression that can do the needful? What is wrong with the foreach on 'wordsToRemove'?

Observe my posted code block. There's a commented line dictionary=wordsToRemove.Select............. I tried alternatively commenting in that one and the foreach loop dictionary.Add. Error is same in both cases.

** read comments added to code block closely Thx.

If you want to remove, let's 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);  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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