C# 如何删除数组中的重复值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10836956/
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 delete duplicate values in an array?
提问by Cippo
Possible Duplicate:
Remove duplicates from array
可能的重复:
从数组中删除重复项
I have an int array which contains a defined number of elements, all positive. I want to get an array from this one where all the elements appear only once. e.g. If the first array was something like {2000,2011,2011,2012,2009,2009,2000}, I want to get this {2000,2011,2012,2009}. How can I do this? I tried lots of things with for loops but I can't manage to do something good.
我有一个 int 数组,其中包含定义数量的元素,所有元素都是正数。我想从这个数组中获取一个数组,其中所有元素只出现一次。例如,如果第一个数组是类似的{2000,2011,2011,2012,2009,2009,2000},我想得到这个{2000,2011,2012,2009}。我怎样才能做到这一点?我用 for 循环尝试了很多东西,但我无法做一些好事。
采纳答案by Tim Schmelter
With LINQ it's easy:
使用 LINQ 很容易:
var intArray = new[] { 2000, 2011, 2011, 2012, 2009, 2009, 2000 };
var uniqueArray = intArray.Distinct().ToArray();
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx
Another way is using Enumerable.GroupBy:
另一种方法是使用Enumerable.GroupBy:
uniqueArray = intArray.GroupBy(i => i).Select(grp => grp.Key).ToArray();
回答by Massimiliano Peluso
you can do the below
您可以执行以下操作
var yourArray = yourArray.Distinct().ToArray();
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx
回答by NominSim
回答by NominSim
Alternative way:
替代方式:
int[] _array = new int[] {1, 2, 1,2}
var myArray = new System.Collections.ArrayList();
foreach(var item in _array){
if (!myArray.Contains(item))
myArray.Add(item);
}

