c#list.OrderBy根本不起作用吗? [英] c# list.OrderBy not working at all?
本文介绍了c#list.OrderBy根本不起作用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很难理解 list.OrderBy
的工作原理,而且我不明白自己在做什么错...我认为这很容易在某个地方犯了一些愚蠢的错误,或者它只是以我不了解的其他方式工作。无论如何,我想做的是根据属性对列表进行排序,我编写了一个简单的程序来说明我的意思。
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);
}
}
}
输出如下: / p>
This gives the output:
1
3
2
我想要输出:
1
2
3
有人可以向我解释为什么不这样做以及如何解决它?我对c#还是很陌生。
Can anybody explain to me why it's not doing this and how I can fix it? I'm quite new with c#.
推荐答案
您 just 需要分配 OrderBy
返回。
list = list.OrderBy(x => x.level).ToList();
这篇关于c#list.OrderBy根本不起作用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文