C# List<T> OrderBy always returning null
Here's my setup.
public class ItemList : List<Item>
{
public void Load() {...}
public void Save() {...}
}
Load reads from an XML file to populate the ItemList
I then attempt to order the item list by a Priority. This is an int? For the test purposes however all the items have a different value.
ItemList itemList = new ItemList();
itemList.Load();
ItemList newItemList = itemList
.OrderBy(item => item.Priority) as ItemList;
return newItemList;
In the above newItemList is always null. itemList has a Count of 7. I've triple checked and all the items in the itemList instance have a priority set.
What am I doing wrong?
I've also tried...
ItemList newItemList = itemList
.OrderBy(item => item.Priority)
.ToList() as 开发者_开发知识库ItemList;
Nothing seems to be working.
Thanks in advance!
The problem is that OrderBy doesn't return an ItemList, it returns an IOrderedEnumerable, and ToList() doesn't return an ItemList, it returns an List. Either way, you're trying to cast both to an ItemList, which they aren't, so you get null.
ItemList someList = (new ItemList {new Item(2), new Item(1), new Item(3)});
//this returns an IOrderedEnumerable<Item>
var result = someList.OrderBy(i => i.Priority);
//this returns a List<Item>
var otherResult = someList.ToList();
Neither OrderBy or ToList returns an ItemList, so the casting returns null, as Joseph pointed out.
As you are inheriting from the List<T>
class, you can just use the Sort method to sort it:
ItemList itemList = new ItemList();
itemList.Load();
itemList.Sort((x, y) => x.Priority.CompareTo(y.Priority));
return itemList;
I think your issue is the " as ItemList".
The LINQ operators doesn't work in-place on your newItemList object. They create and return new objects. If you want to do in-place sorting you should use the Sort() method of List<>.
精彩评论