Search code examples
c#linqsortingoopreturn-value

How to return strings that are sorted by their number(using Linq) in c#


I have a question about how to print only texts that are sorted by number using Linq

for example, if I wanted to print only the names of the mountain, which would be sorted by the height of the mountain

NOTE: I just invented a Mountain class that would contain only 2 variables - the height and the name of the mountain (including the constructor, toString() etc...)

input:

Mountain mountain1 = new Mountain("Mountain1",3000);
Mountain mountain2 = new Mountain("Mountain2",2000);
Mountain mountain3 = new Mountain("Mountain3",6500);
  

output:

Mountain3
Mountain1
Mountain2

Solution

  • if you can you make a List/Array ect. with those objects, you can order them By Property. By default it would return ascending values, thats why in your case you would need OrderByDescending.

    var mountains = new []
    {
       new Mountain("Mountain1",3000),
       new Mountain("Mountain2",2000),
       new Mountain("Mountain3",6500),
    };
    
    mountains.OrderByDescending(x => x.Height).Select(x => x.Name);
    

    The code as a working Fiddle can be found here:

    https://dotnetfiddle.net/szA14I