如何从 C# 中的集合中获取唯一值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1205807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get unique values from a collection in C#?
提问by George2
I am using C# + VSTS2008 + .Net 3.0. I have an input as a string array. And I need to output the unique strings of the array. Any ideas how to implement this efficiently?
我正在使用 C# + VSTS2008 + .Net 3.0。我有一个输入作为字符串数组。我需要输出数组的唯一字符串。任何想法如何有效地实现这一点?
For example, I have input {"abc", "abcd", "abcd"}, the output I want to be is {"abc", "abcd"}.
例如,我输入了 {"abc", "abcd", "abcd"},我想要的输出是 {"abc", "abcd"}。
采纳答案by Philippe Leybaert
Using LINQ:
使用 LINQ:
var uniquevalues = list.Distinct();
That gives you an IEnumerable<string>
.
这会给你一个IEnumerable<string>
.
If you want an array:
如果你想要一个数组:
string[] uniquevalues = list.Distinct().ToArray();
If you are not using .NET 3.5, it's a little more complicated:
如果您使用的不是 .NET 3.5,则稍微复杂一些:
List<string> newList = new List<string>();
foreach (string s in list)
{
if (!newList.Contains(s))
newList.Add(s);
}
// newList contains the unique values
Another solution (maybe a little faster):
另一个解决方案(可能快一点):
Dictionary<string,bool> dic = new Dictionary<string,bool>();
foreach (string s in list)
{
dic[s] = true;
}
List<string> newList = new List<string>(dic.Keys);
// newList contains the unique values
回答by Kobi
Another option is to use a HashSet
:
另一种选择是使用HashSet
:
HashSet<string> hash = new HashSet<string>(inputStrings);
I think I'd also go with linq, but it's also an option.
我想我也会使用 linq,但这也是一种选择。
Edit:
You've update the question to 3.0, maybe this will help:
Using HashSet in C# 2.0, compatible with 3.5
编辑:
您已将问题更新为 3.0,也许这会有所帮助:
在 C# 2.0 中使用 HashSet,与 3.5 兼容
回答by shahjapan
You can go with Linq its short and sweet but in case u don't wanna LINQ try second Option HashSet
你可以使用 Linq 它的简短和甜蜜,但如果你不想 LINQ 尝试第二个 Option HashSet
Option 1:
选项1:
string []x = new string[]{"abc", "abcd", "abcd"};
IEnumerable<string> y = x.Distinct();
x = Enumerable.ToArray(y);
Option 2:
选项 2:
HashSet<string> ss = new HashSet<string>(x);
x = Enumerable.ToArray(ss);