问题描述
所以我今天遇到了一个有趣的问题.我们有一个返回 IList 的 WCF Web 服务.没什么大不了的,直到我想对它进行排序.
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 接口没有内置排序方法.
Turns out the IList interface doesn't have a sort method built in.
我最终使用了 ArrayList.Adapter(list).Sort(new MyComparer())
方法来解决这个问题,但它对我来说似乎有点贫民窟".
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.
我尝试编写扩展方法,也尝试从 IList 继承并实现我自己的 Sort() 方法以及转换为 List,但这些方法似乎都不太优雅.
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 进行排序
So my question is, does anyone have an elegant solution to sorting an IList
推荐答案
如何使用 LINQ To Objects 为您排序?
How about using LINQ To Objects to sort for you?
假设你有一个 IList
,并且汽车有一个 Engine
属性,我相信你可以这样排序:
Say you have a IList<Car>
, and the car had an Engine
property, I believe you could sort as follows:
from c in list
orderby c.Engine
select c;
您确实需要在这里快速获得答案.由于我提出的语法与其他答案略有不同,因此我将留下我的答案 - 但是,所提出的其他答案同样有效.
这篇关于在 C# 中对 IList 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!