在循环遍历一系列值或字段时,我使用的是不同的值。
Dictionary<string, int> _ddistinctValues = new Dictionary<string, int>();
foreach(string _word in _words) {
if(!_ddistinctValues.ContainsKey(_word)) {
_ddistinctValues.Add(_word, 1);
}
}有没有更好的方法来做到这一点而不保存"1“整数值以节省空间?我正在使用hashtable来更快地获取不同的值。也许散列没有值的单词名,只有不同的键?在C#中有没有可以做到这一点的类?
这不是一个大问题。只是想知道。
谢谢。
发布于 2012-01-08 08:55:59
只需使用LINQ并调用列表上的Distinct()即可。您可能希望将结果放入另一个列表中。
var distinctWords = _words.Distinct().ToList();这将在内部使用HashSet来确定唯一性,这将是您感兴趣的集合。
发布于 2012-01-08 08:56:34
是的,HashSet是为您准备的类。
发布于 2012-01-08 08:56:45
你要找的是HashSet<string>。
https://stackoverflow.com/questions/8774477
复制相似问题