我有一个物品清单。对象具有不同的字段,例如年龄和名称
现在,有时我想按姓名排序,有时按年龄排序。附加,有时递增,有时递减。
现在我明白了,我应该在对象中实现Comparable接口并重写CompareTo方法。
但是,当我想支持各种排序订单时,我该如何做到这一点?
我是否必须在对象中设置排序顺序,或者是否可以通过排序方法调用传递排序顺序?
我有一个物品清单。对象具有不同的字段,例如年龄和名称
现在,有时我想按姓名排序,有时按年龄排序。附加,有时递增,有时递减。
现在我明白了,我应该在对象中实现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);
What is the use of default keyword in C#? Is it introduced in C# 3.0 ?
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. ...
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 ...
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 ...
I have two EF entities. One has a property called HouseNumber. The other has two properties, one called StartHouseNumber and one called EndHouseNumber. I want to create a many to many association ...
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, ...
Since I cannot order my dictionary, what is the best way of going about taking key value pairs and also maintaing an index?
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. ...