C# 从列表中获取唯一项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1388361/
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
Getting unique items from a list
提问by domgreen
What is the fastest / most efficient way of getting all the distinct items from a list?
从列表中获取所有不同项目的最快/最有效的方法是什么?
I have a List<string>
that possibly has multiple repeating items in it and only want the unique values within the list.
我有一个List<string>
可能有多个重复项,并且只想要列表中的唯一值。
采纳答案by Vinay Sajip
Use a HashSet<T>
. For example:
使用一个HashSet<T>
. 例如:
var items = "A B A D A C".Split(' ');
var unique_items = new HashSet<string>(items);
foreach (string s in unique_items)
Console.WriteLine(s);
prints
印刷
A B D C
回答by LukeH
You can use the Distinct
method to return an IEnumerable<T>
of distinct items:
您可以使用该Distinct
方法返回一个IEnumerable<T>
不同的项目:
var uniqueItems = yourList.Distinct();
And if you need the sequence of unique items returned as a List<T>
, you can add a call to ToList
:
如果您需要作为 a 返回的唯一项目序列List<T>
,您可以添加对 的调用ToList
:
var uniqueItemsList = yourList.Distinct().ToList();
回答by Noldorin
Apart from the Distinct
extension method of LINQ, you could use a HashSet<T>
object that you initialise with your collection. This is most likely more efficient than the LINQ way, since it uses hash codes (GetHashCode
) rather than an IEqualityComparer
).
除了Distinct
LINQ的扩展方法之外,您还可以使用HashSet<T>
您的集合初始化的对象。这很可能比 LINQ 方式更有效,因为它使用哈希码 ( GetHashCode
) 而不是IEqualityComparer
)。
In fact, if it's appropiate for your situation, I would just use a HashSet
for storing the items in the first place.
事实上,如果它适合您的情况,我会首先使用 aHashSet
来存储项目。
回答by Murilo Beltrame
In .Net 2.0 I`m pretty sure about this solution:
在 .Net 2.0 中,我非常确定这个解决方案:
public IEnumerable<T> Distinct<T>(IEnumerable<T> source)
{
List<T> uniques = new List<T>();
foreach (T item in source)
{
if (!uniques.Contains(item)) uniques.Add(item);
}
return uniques;
}