如何对iList进行排序(使用linq或不使用)

Sev*_*Sev 4 .net c# sorting ilist interface

可能重复:
在C#中对IList进行排序

我有以下方法,我需要对传递给它的iList对象进行排序(在此方法中).我尝试过linq但是因为它是一个界面我会收到错误.

提前致谢

private void AddListToTree(ComponentArt.Web.UI.TreeView treeView, IList list)
{
//NEED TO SORT THE LIST HERE
}
Run Code Online (Sandbox Code Playgroud)

请注意我的类型是动态的.

我想我应该创建一个临时集合,从我的IList实例填充,排序,获取支持IList的对象的适当实例,并使用它而不是我应该保留的IList的非排序实例.所以我试着得到如下类型:

Type[] listTypes = list.GetType().GetGenericArguments();
Type listType = null;
if (listTypes.Length > 0)
{
listType = listTypes[0];
}
Run Code Online (Sandbox Code Playgroud)

但我不能用这种类型创建一个新的List

Mar*_*ers 8

您应该使用通用形式IList来使用LINQ扩展方法:

private void AddListToTree<T>(ComponentArt.Web.UI.TreeView treeView,
                              IList<T> list)
{
    var orderedList = list.OrderBy(t => t);
    // ...
}
Run Code Online (Sandbox Code Playgroud)

如果您无法修改方法的签名但是您知道对象的类型,则IList可以使用Cast:

private void AddListToTree(ComponentArt.Web.UI.TreeView treeView,
                           IList list)
{
    var orderedList = list.Cast<SomeType>().OrderBy(x => x);
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • @SevAbedi,备份.你不能改变签名的原因是什么?这三个类共享相同的基类或接口吗?您的给定`IList`是否会混合,同时包含不同类型的对象?除非为问题提供更多细节,否则很难制定解决方案. (3认同)