[英]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.