如何在List <int>中找到重复的整数并删除其中一个?</int>

时间:2014-07-19 21:11:07

标签: c# list duplicates

初​​学者;新手级别的问题。下面是生成30个随机数的代码,按升序对它们进行排序,然后按降序对它们进行排序。最后一个目标是在列表中找到重复项并删除其中一个(例如,如果有两个27,我想删除一个并离开另一个)。

    static void Main(string[] args)
    {

        Random randomNum = new Random();
        List<int> numbers = new List<int>();

        for (int i = 0; i < 30; i += 1)
            numbers.Add(randomNum.Next(1, 100));

        Console.Write("List of random numbers:");
        foreach (var number in numbers)
            Console.Write(" {0} ", number);

        var sorted =
            from number in numbers
            orderby number
            select number;

        Console.WriteLine();
        Console.Write("List in ascending order:");
        foreach (var element in sorted)
            Console.Write(" {0} ", element);

        var sortdescending =
            from number in numbers
            orderby number descending
            select number;

        Console.WriteLine();
        Console.Write("List in descending order:");
        foreach (var element in sortdescending)
            Console.Write(" {0} ", element);

2 个答案:

答案 0 :(得分:-1)

int是内置类型,然后你可以使用简单的:

numbers = numbers.Distinct();

但如果您有课程,则可以覆盖两种方法:等于 GetHashCode

答案 1 :(得分:-2)

别忘了使用

using System.Linq;
然后(如康拉德所说)

var distinctNumbers = numbers.Distinct();