简体   繁体   English

对列表列表进行排序C#

[英]Sorting a list of lists C#

I have the following list of lists that I wish to sort by price: 我有以下列表,希望按价格排序:

List<object> StationList = new List<object>();
List<object> ListEntry = new List<object>();

ListEntry.Add(Name);  //string
ListEntry.Add(Area);  //string
ListEntry.Add(Price); //int

StationList.Add(ListEntry);

I have tried to sort it with: 我试图用以下方式对其进行排序:

List<object> SortedList = StationList.OrderBy(list => list[2]);

This gives me the error: 这给了我错误:

//Cannot apply indexing with [] to an expression of type 'object'

How do I sort this list of lists? 如何对列表列表进行排序?

As pointed out in the comments, using a List<object> is a bad idea. 正如评论中指出的那样,使用List<object>是一个坏主意。 Especially when used as a container for data that could (and should) be kept in a better structure. 特别是当用作可以(并且应该)以更好的结构保存数据的容器时。

It looks like your StationList should actually be a list of stations. 看来您的StationList实际上应该是电台列表。 So it would be a good idea to create a structure that describes a station. 因此,创建一个描述站点的结构是一个好主意。 Maybe something like this: 也许是这样的:

public class Station
{
    public string Name { get;set; }
    public string Area { get;set; }
    public int Price { get;set; } /* although 'decimal' might be a better type */
}

Now the StationList can be defined and initialized as: 现在可以定义StationList并将其初始化为:

List<Station> StationList = new List<Station>();
/* although you could just call it 'Stations' */

Now create a new Station and fill it with data and add it to the StationList : 现在创建一个新的Station并用数据填充并将其添加到StationList

Station station = new Station();
station.Name = Name;
station.Area = Area;
station.Price = Price;

StationList.Add(station);

And if you want to order the list of stations by price, you can do it like: 如果您想按价格订购电视台列表,可以按照以下步骤操作:

List<Station> SortedList = StationList.OrderBy(entry => entry.Price).ToList();

Which (imho) is more readable than list => list[2] . 哪个(imho)比list => list[2]更易读。 Also, the whole thing is type safe, which means that you can be sure, that StationList will only contain instances of type Station (or types derived of Station ) and you can access the Name , Area and Price properties of those instances directly, without having to cast them from type Object or having to remember which "property" is at which index in the list. 同样,整个过程都是安全类型,这意味着您可以确定StationList将仅包含Station类型的实例(或Station派生的类型),并且您可以直接访问这些实例的NameAreaPrice属性,而无需必须从Object类型Object转换它们,或者必须记住列表中哪个索引位于哪个“属性”。

And if your going to work with the Station informations further, I'd guess you'll have a much easier time if you're using that class instead of List<object> . 而且,如果您要进一步使用Station信息,我想如果您使用该类而不是List<object>话,您会更轻松。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM