如何从 C# 中的数组中获取不同的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8816001/
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 04:35:45  来源:igfitidea点击:

How to get distinct values from an array in C#?

c#

提问by AK Jani

Possible Duplicate:
Remove duplicates from array

可能的重复:
从数组中删除重复项

How to get distinct values from an array in C#

如何从C#中的数组中获取不同的值

回答by Darin Dimitrov

You could use the .Distinct()extension method.

您可以使用.Distinct()扩展方法。

var collectionWithDistinctElements = oldArray.Distinct().ToArray();

回答by Samich

Using Distinct()function:

使用Distinct()功能:

var distinctArray = myArray.Distinct().ToArray();

回答by agarcian

Use the Distinctmethod in LINQ.

使用DistinctLINQ 中的方法。

See http://msdn.microsoft.com/en-us/library/bb348436.aspx

请参阅http://msdn.microsoft.com/en-us/library/bb348436.aspx

            List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 };

            IEnumerable<int> distinctAges = ages.Distinct();

            Console.WriteLine("Distinct ages:");

            foreach (int age in distinctAges)
            {
                Console.WriteLine(age);
            }

            /*
             This code produces the following output:

             Distinct ages:
             21
             46
             55
             17
            */

回答by Amar Palsapure

Distinctshould suffice your problem, but if you are doing this on custom object you will need to implement IEquatable<T>and will need to override GetHashCode()method to make it work.

Distinct应该足以解决您的问题,但是如果您在自定义对象上执行此操作,则需要实现IEquatable<T>并且需要覆盖GetHashCode()方法以使其工作。