使用哈希表的不同值

ief*_*fpw 2 c# linq hashset

在循环遍历值列表或字段时,我正在做不同的值.

Dictionary<string, int> _ddistinctValues = new Dictionary<string, int>();

foreach(string _word in _words) {
 if(!_ddistinctValues.ContainsKey(_word)) {
    _ddistinctValues.Add(_word, 1);
 }
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来实现这一点而不保存"1"整数值以节省空间?我正在使用哈希表来更快地获得不同的值.也许哈希没有值的wordname,只是不同的键?C#中有一个类可以做到这一点吗?

这不是一个大问题.就是想.

谢谢.

Jef*_*ado 5

只需使用LINQ并调用Distinct()列表即可.您可能希望将结果放入另一个列表中.

var distinctWords = _words.Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)

这将在内部使用a HashSet<T>来确定您将感兴趣的集合的唯一性.