Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# list.OrderBy not working at all? [duplicate]

Tags:

c#

I have a hard time understanding how the list.OrderBy works and I don't understand what I'm doing wrong... I think it's something easy that I made some stupid mistake somewhere or that it's just working in another way than I understood. Anyways, what I want to do is sort a list from an attribute, I've made a simple program to illustrate what I mean.

class Hero
    {
        public int level;
        public Hero(int level)
        {
            this.level = level;
        }

        static void Main(string[] args)
        {
            Hero hero1 = new Hero(1);
            Hero hero3 = new Hero(3);
            Hero hero2 = new Hero(2);

            List<Hero> list = new List<Hero>();
            list.Add(hero1);
            list.Add(hero3);
            list.Add(hero2);
            list.OrderBy(x => x.level).ToList();
            foreach (Hero x in list)
            {
                Console.WriteLine(x.level);
            }
        }
    }

This gives the output:

1
3
2 

While I would like the output:

1
2
3

Can anybody explain to me why it's not doing this and how I can fix it? I'm quite new with c#.

like image 605
Benji Avatar asked Dec 06 '15 11:12

Benji


3 Answers

You just need to assign what OrderBy returns.

list = list.OrderBy(x => x.level).ToList();
like image 105
Soner Gönül Avatar answered Oct 27 '22 01:10

Soner Gönül


You should return result from list.OrderBy(x => x.level) to the same list:

list = list.OrderBy(x => x.level).ToList();
like image 27
marcinax Avatar answered Oct 26 '22 23:10

marcinax


OrderBy() does not sort the IEnumerable that you input, but returns a new IOrderedEnumerable

This will work:

List<Hero> ordered = list.OrderBy(x => x.level).ToList();
foreach (Hero x in ordered)
{
    Console.WriteLine(x.level);
}

Or even

foreach (Hero x in list.OrderBy(x => x.level))
{
    Console.WriteLine(x.level);
}
like image 42
Residuum Avatar answered Oct 27 '22 00:10

Residuum