-1

Beginner; novice-level problem. Here is the code that generates 30 random numbers, sorts them in ascending order, and then sorts them in descending order. The last objective is to find duplicates in the list and remove one of them (e.g., if there are two 27's, I want to remove one and leave the other).

    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);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
user3500004
  • 17
  • 2
  • 3

2 Answers2

0

int is buil-in type, then you can use simple:

numbers = numbers.Distinct();

but if you have class, you can then override two methods: Equals and GetHashCode

Marek Woźniak
  • 1,766
  • 16
  • 34
-1

Don't forget to use

using System.Linq;

then (as Konrad said)

var distinctNumbers = numbers.Distinct();
George Vovos
  • 7,563
  • 2
  • 22
  • 45
  • Sorry the question was unclear. You are right: no matter how many instances of x there are, I only want one displayed in the final list. The solution involving numbers.Distinct() sounds helpful, but I don't know how to use it in the code. I wish I was smarter, but I'm not, that's why I'm asking questions. I've been on Google, etc., since 9:30 this morning, consulted textbooks, watched instructional videos, emailed a coder acquaintance...would really appreciate any help you might be willing to offer. – user3500004 Jul 19 '14 at 21:40
  • @user3500004, then edit your question to be more clear and allow to remove downvotes from those correct answers. – Konrad Kokosa Jul 19 '14 at 21:45
  • I have a list of random numbers. They've been sorted, now I want to find and remove the duplicates from the list. I don't know how to do that. var distinctNumbers = numbers.Distinct(); may very well be the key to this, but I don't know how to put that into lines of code that will eliminate the duplicates. – user3500004 Jul 19 '14 at 21:54