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?
In C#, an IEnumerable can be converted to a List through the following lines of code: IEnumerable enumerable = Enumerable. Range(1, 300); List asList = enumerable. ToList();
Use the ToList() Method to Convert an IEnumerable to a List in C# Copy Enumerable.
IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.
IEnumerable<T> is an interface that represents a sequence. Now; collections can usually be used as sequences (so... List<T> implements IEnumerable<T> ), but the reverse is not necessarily true. In fact, it isn't strictly required that you can even iterate a sequence ( IEnumerable<T> ) more than once.
If your collection type implements IList<T>
(to be able to Add()
to it) you could write an extension method:
public static Extensions
{
public static TColl ToTypedCollection<TColl, T>(this IEnumerable ien)
where TColl : IList<T>, new()
{
TColl collection = new TColl();
foreach (var item in ien)
{
collection.Add((T) item);
}
return collection;
}
}
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>
called To<YourCollectionType>
which would take the IEnumerable<T>
and then pass it to the constructor of your type and return that.
No. You could follow the pattern established by the ToList and ToDictionary extension methods - write a similar extension method to load up your own collection type from IEnumerable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With