I am using extension methods OrderBy and ThenBy to sort my custom collection on multiple fields. This sort does not effect the collection but instead returns and IEnumberable. I am unable to cast the IEnumerable result to my custom collection. Is there anyway to change the order of my collection or convert the IEnumerable result to my custom collection?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
No there isn't. When you use the query operators, it doesn't use instances of the original collection to generate the enumeration. Rather, it uses private implementations (possibly anonymous, possibly not) to provide this functionality.
If you want it in your original collection, you should have a constructor on the type which takes an
IEnumerable<T>
(or whatever your collection stores, if it is specific) and then pass the query to the constructor.You can then use this to create an extension method for
IEnumerable<T>
calledTo<YourCollectionType>
which would take theIEnumerable<T>
and then pass it to the constructor of your type and return that.If you look in the System.Linq.Enumerable class there are a few extension methods that will aloow you to convert you IEnumerable type to either an Array, ToList
You could follow this approach and create a custom extension method that will convert to your custom collection
You can initialize a list with IEnumerable:
If items is of type IEnumerable, you can create a list like this:
or you could simply call items.ToList():
Enumerables and collections are fairly different beasts.
Enumerations only allow to, well, enumerate while collections have index-based accessors, Count-property and the like. To create a collection you will actually have to enumerate the IEnumerable. Typical Collections like List<T> will have a constructor that accept an IEnumerable. Nonetheless, the enumeration will be performed.
LINQ is cool because it treats the source-collections like this as immutable - it is not modifying them. Using the extension methods simply enumerates them in the alternate order you specify - you are not building a NEW custom list in this way.
I would suggest two options:
If your collection type implements
IList<T>
(to be able toAdd()
to it) you could write an extension method: