English 中文(简体)
用C#对列表进行排序(使用各种参数)
原标题:Sorting a list in C# (with various parameters)

我有一个物品清单。对象具有不同的字段,例如年龄和名称

现在,有时我想按姓名排序,有时按年龄排序。附加,有时递增,有时递减。

现在我明白了,我应该在对象中实现Comparable接口并重写CompareTo方法。

但是,当我想支持各种排序订单时,我该如何做到这一点?

我是否必须在对象中设置排序顺序,或者是否可以通过排序方法调用传递排序顺序?

最佳回答

方法调用可以做任何事情;不需要比较器:

list.Sort((x,y)=>string.Compare(x.Name,y.Name));

list.Sort((x,y)=>y.Age.CompareTo(x.Age)); // desc
list.Sort((x,y)=>x.Age.CompareTo(y.Age)); // asc

请注意,第二个是递减的,通过在比较中交换x/y。

问题回答

如果您使用的是<code>列表<;T>,并且您想在适当的位置对列表进行排序,则sort函数提供一个重载,该重载接受Comparison<;T>。您可以使用它为列表提供不同的比较。

例如,要按年龄排序:

list.Sort((x, y) => x.Age.CompareTo(y.Age));

要按名称排序,请执行以下操作:

list.Sort((x, y) => string.Compare(x.Name, y.Name));

要按降序排序,只需反转参数即可。

或者,您可以使用LINQ针对您的列表创建各种查询,这些查询以您喜欢的任何顺序提供结果,但这不会对基本列表产生任何影响(好坏取决于您):

var byAge = list.OrderBy(x => x.Age);
var byName = list.OrderBy(x => x.Name);

要按降序排序,请使用OrderByDescending代替OrderBy

您也可以使用LINQ来处理此问题:

var sortedByAge = myList.OrderBy(i => i.Age);
var sortedByName = myList.OrderBy(i => i.Name);

如果您想就地处理排序,可以使用列表<;T>;。排序(比较<;T>;)

// Sort by Age
myList.Sort( (l, r) => l.Age.CompareTo(r.Age) );
// Sort by Name
myList.Sort( (l, r) => l.Name.CompareTo(r.Name) );

您可以使用linq对对象数据进行排序

像这样的东西

var query = from cust in customers
            orderby cust.Age ascending
            select cust;

您也可以使用

list.OrderByDescending(a => a.Age);

list.OrderByAscending(a => a.Age);




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...