在 C# 中对 IList 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting an IList in C#
提问by lomaxx
So I came across an interesting problem today. We have a WCF web service that returns an IList. Not really a big deal until I wanted to sort it.
所以我今天遇到了一个有趣的问题。我们有一个返回 IList 的 WCF Web 服务。在我想对它进行排序之前,这没什么大不了的。
Turns out the IList interface doesn't have a sort method built in.
原来 IList 接口没有内置排序方法。
I ended up using the ArrayList.Adapter(list).Sort(new MyComparer())
method to solve the problem but it just seemed a bit "ghetto" to me.
我最终使用该ArrayList.Adapter(list).Sort(new MyComparer())
方法来解决问题,但对我来说似乎有点“贫民窟”。
I toyed with writing an extension method, also with inheriting from IList and implementing my own Sort() method as well as casting to a List but none of these seemed overly elegant.
我尝试编写扩展方法,也尝试从 IList 继承并实现我自己的 Sort() 方法以及转换为 List,但这些方法似乎都不太优雅。
So my question is, does anyone have an elegant solution to sorting an IList
所以我的问题是,有没有人有一个优雅的解决方案来对 IList 进行排序
采纳答案by Brad Leach
How about using LINQ To Objects to sort for you?
使用 LINQ To Objects 为您排序怎么样?
Say you have a IList<Car>
, and the car had an Engine
property, I believe you could sort as follows:
假设您有一个IList<Car>
,并且汽车有一个Engine
属性,我相信您可以按以下方式排序:
from c in list
orderby c.Engine
select c;
Edit: You do need to be quick to get answers in here. As I presented a slightly different syntax to the other answers, I will leave my answer - however, the other answers presented are equally valid.
编辑:您确实需要在这里快速获得答案。由于我提出了与其他答案略有不同的语法,因此我将留下我的答案——但是,所提出的其他答案同样有效。
回答by Leon Bambrick
You're going to have to do something like that i think (convert it into a more concrete type).
你将不得不做我认为类似的事情(将其转换为更具体的类型)。
Maybe take it into a List of T rather than ArrayList, so that you get type safety and more options for how you implement the comparer.
也许将其放入 T 的列表而不是 ArrayList 中,以便您获得类型安全和更多关于如何实现比较器的选项。
回答by lubos hasko
Convert your IList
into List<T>
or some other generic collection and then you can easily query/sort it using System.Linq
namespace (it will supply bunch of extension methods)
将您的转换IList
为List<T>
或其他一些通用集合,然后您可以使用System.Linq
命名空间轻松查询/排序它(它将提供一堆扩展方法)
回答by Mark Cidade
You can use LINQ:
您可以使用 LINQ:
using System.Linq;
IList<Foo> list = new List<Foo>();
IEnumerable<Foo> sortedEnum = list.OrderBy(f=>f.Bar);
IList<Foo> sortedList = sortedEnum.ToList();
回答by ICR
Here's an example using the stronger typing. Not sure if it's necessarily the best way though.
这是使用更强类型的示例。不确定这是否一定是最好的方法。
static void Main(string[] args)
{
IList list = new List<int>() { 1, 3, 2, 5, 4, 6, 9, 8, 7 };
List<int> stronglyTypedList = new List<int>(Cast<int>(list));
stronglyTypedList.Sort();
}
private static IEnumerable<T> Cast<T>(IEnumerable list)
{
foreach (T item in list)
{
yield return item;
}
}
The Cast function is just a reimplementation of the extension method that comes with 3.5 written as a normal static method. It is quite ugly and verbose unfortunately.
Cast 函数只是作为普通静态方法编写的 3.5 附带的扩展方法的重新实现。不幸的是,它非常丑陋和冗长。
回答by Amy B
In VS2008, when I click on the service reference and select "Configure Service Reference", there is an option to choose how the client de-serializes lists returned from the service.
在 VS2008 中,当我单击服务引用并选择“配置服务引用”时,有一个选项可以选择客户端如何反序列化从服务返回的列表。
Notably, I can choose between System.Array, System.Collections.ArrayList and System.Collections.Generic.List
值得注意的是,我可以在 System.Array、System.Collections.ArrayList 和 System.Collections.Generic.List 之间进行选择
回答by Amy B
Found a good post on this and thought I'd share. Check it out HERE
找到了一个很好的帖子,并认为我会分享。在这里查看
Basically.
基本上。
You can create the following class and IComparer Classes
您可以创建以下类和 IComparer 类
public class Widget {
public string Name = string.Empty;
public int Size = 0;
public Widget(string name, int size) {
this.Name = name;
this.Size = size;
}
}
public class WidgetNameSorter : IComparer<Widget> {
public int Compare(Widget x, Widget y) {
return x.Name.CompareTo(y.Name);
}
}
public class WidgetSizeSorter : IComparer<Widget> {
public int Compare(Widget x, Widget y) {
return x.Size.CompareTo(y.Size);
}
}
Then If you have an IList, you can sort it like this.
那么如果你有一个IList,你可以这样排序。
List<Widget> widgets = new List<Widget>();
widgets.Add(new Widget("Zeta", 6));
widgets.Add(new Widget("Beta", 3));
widgets.Add(new Widget("Alpha", 9));
widgets.Sort(new WidgetNameSorter());
widgets.Sort(new WidgetSizeSorter());
But Checkout this site for more information... Check it out HERE
但是请查看此站点以获取更多信息...查看此处
回答by Amy B
using System.Linq;
var yourList = SomeDAO.GetRandomThings();
yourList.ToList().Sort( (thing, randomThing) => thing.CompareThisProperty.CompareTo( randomThing.CompareThisProperty ) );
That's pretty !ghetto.
这很漂亮!贫民窟。
回答by John
Found this thread while I was looking for a solution to the exact problem described in the original post. None of the answers met my situation entirely, however. Brody's answer was pretty close. Here is my situation and solution I found to it.
在我寻找原始帖子中描述的确切问题的解决方案时找到了这个线程。然而,没有一个答案完全符合我的情况。布罗迪的回答非常接近。这是我的情况和我找到的解决方案。
I have two ILists of the same type returned by NHibernate and have emerged the two IList into one, hence the need for sorting.
我有两个由 NHibernate 返回的相同类型的 IList,并将两个 IList 合二为一,因此需要进行排序。
Like Brody said I implemented an ICompare on the object (ReportFormat) which is the type of my IList:
就像布罗迪说的,我在对象 (ReportFormat) 上实现了一个 ICompare,它是我的 IList 类型:
public class FormatCcdeSorter:IComparer<ReportFormat>
{
public int Compare(ReportFormat x, ReportFormat y)
{
return x.FormatCode.CompareTo(y.FormatCode);
}
}
I then convert the merged IList to an array of the same type:
然后我将合并的 IList 转换为相同类型的数组:
ReportFormat[] myReports = new ReportFormat[reports.Count]; //reports is the merged IList
Then sort the array:
然后对数组进行排序:
Array.Sort(myReports, new FormatCodeSorter());//sorting using custom comparer
Since one-dimensional array implements the interface System.Collections.Generic.IList<T>
, the array can be used just like the original IList.
由于一维数组实现了接口System.Collections.Generic.IList<T>
,所以数组可以像原来的IList一样使用。
回答by Yoav
Is this a valid solution?
这是一个有效的解决方案吗?
IList<string> ilist = new List<string>();
ilist.Add("B");
ilist.Add("A");
ilist.Add("C");
Console.WriteLine("IList");
foreach (string val in ilist)
Console.WriteLine(val);
Console.WriteLine();
List<string> list = (List<string>)ilist;
list.Sort();
Console.WriteLine("List");
foreach (string val in list)
Console.WriteLine(val);
Console.WriteLine();
list = null;
Console.WriteLine("IList again");
foreach (string val in ilist)
Console.WriteLine(val);
Console.WriteLine();
The result was: IList B A C
结果是:IList B A C
List A B C
列表 A B C
IList again A B C
IList 再次 A B C