Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an iList (With linq or without) [duplicate]

Possible Duplicate:
Sorting an IList in C#

I have the following method and I need to sort the iList object that is being passed to it (inside this method). I have tried linq but since it's an interface I'm getting errors.

Thanks in advance

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

Please note that my type is Dynamic.

I think I should create a temporary collection, populate if from my instance of IList, sort it, get appropriate instance of the object supporting IList and use it instead of my non-sorted instance of IList which I should leave intact. So I tried getting the type like following:

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

But I cannot create a new List with this type

like image 644
Sev Avatar asked Dec 22 '22 05:12

Sev


1 Answers

You should use the generic form of IList to be able to use the LINQ extension methods:

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

If you can't modify the method's signature but you know the type of the objects in the IList, you can use Cast:

private void AddListToTree(ComponentArt.Web.UI.TreeView treeView,
                           IList list)
{
    var orderedList = list.Cast<SomeType>().OrderBy(x => x);
    // ...
}
like image 172
Mark Byers Avatar answered Jan 06 '23 15:01

Mark Byers