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#.
You just need to assign what OrderBy
returns.
list = list.OrderBy(x => x.level).ToList();
You should return result from list.OrderBy(x => x.level)
to the same list:
list = list.OrderBy(x => x.level).ToList();
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With