如何在C#中对此列表进行排序? [英] How do I sort this list in C#?

查看:108
本文介绍了如何在C#中对此列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在尝试使用以下代码对C#中的列表进行排序:



 bodylist = bodylist.OrderBy(a => a.Movable).ThenBy(a => a.Name); 





我尝试排序的列表 - 在同一个类中声明 - 看起来像这样:



静态私人列表< Body> bodylist = new List< Body>(); 

static public IReadOnlyList< Body> Bodylist
{
//以下代码禁止其他代码通过Add或类似代码进行更改,
//但基本上它是没有setter的普通属性。
get {return new ReadOnlyCollection< Body>(bodylist); }
}





找到Body对象(其属性Movable和Name出现)。 />


但是,我可以让代码执行的唯一方法是删除等号左边的blist。如果我这样做,列表不会排序。



我上面代码的错误信息是:



无法隐式转换类型'系统.Linq.IOrderedEnumerable< xenia2d_wpf.body>'to'System.Collections.Generic.List< xenia2d_wpf.body>'。存在显式转换(你是否错过演员?)





我的目标是对列表进行排序,首先是布尔值(可移动)然后是名称。



I我确定有一些简单的语法错误,但我不知道它是什么,所以我很感激一些帮助。 :)



谢谢!



Petter



我尝试了什么:



我搜索了类似的例子,但只发现了返回列表的例子,所以他们没有真正符合我的目的。

解决方案

解决方案在错误消息中描述。 OrderBy返回IEnumerable

请参阅链接:可枚举。 OrderBy(TSource,TKey)方法(IEnumerable(TSource),Func(TSource,TKey))(System.Linq) [ ^ ]然后你应该转换为列表哪个是bodylist的类型。

静态私有列表< Body> bodylist = new List< Body>(); 
bodylist = bodylist.OrderBy(a => a.Movable).ThenBy(a => a.Name) .ToList();


Hi,

I am trying to sort a list in C#, using the following code:

bodylist = bodylist.OrderBy(a => a.Movable).ThenBy(a => a.Name);



The List I try to sort - declared in the same class - looks like this:

static private List<Body> bodylist = new List<Body>();

static public IReadOnlyList<Body> Bodylist
{
    //the following code prohibits other code to make changes via Add or similar,
    //but basically it's a normal property without a setter.
    get { return new ReadOnlyCollection<Body>(bodylist); }
}



The Body object is found (its properties Movable and Name show up).

However, the only way I can get the code to execute is if I remove the blist to the left of the equal sign. And if I do that, the list isn't sorted.

The error message I get with the code above is:

"Cannot implicitly convert type 'System.Linq.IOrderedEnumerable<xenia2d_wpf.body>' to 'System.Collections.Generic.List<xenia2d_wpf.body>'. An explicit conversion exists (are you missing a cast?)"


My object was to sort the list, first by a boolean (Movable) and then on Name.

I'm sure there is some simple syntax mistake but I don't know what it is, so I'd appreciate some help. :)

Thanks!

Petter

What I have tried:

I have searched for similar examples, but only found examples returning lists, so they don't really match what I'm trying to do.

解决方案

Hi, the solution is described in the error message. OrderBy retuns an IEnumerable
see link: Enumerable.OrderBy(TSource, TKey) Method (IEnumerable(TSource), Func(TSource, TKey)) (System.Linq)[^] where then you should cast to list which is the type of bodylist.

static private List<Body> bodylist = new List<Body>();
bodylist = bodylist.OrderBy(a => a.Movable).ThenBy(a => a.Name).ToList();


这篇关于如何在C#中对此列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆