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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:28:07  来源:igfitidea点击:

How to delete duplicate values in an array?

c#

提问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

回答by NominSim

In addition to the other answers, you may want to look at a HashSet, especially if you know ahead of time you will have duplicate values.

除了其他答案之外,您可能还想查看 a HashSet,特别是如果您提前知道会有重复值。

回答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);
    }