.NET compiler will not implicitly convert System.Linq.IOrderedEnumerable<T>
to System.Collections.Generic.List<T>
An explicit cast :
using System.Collections.Generic;
var items = new List<MyType>;
var selectedItems =
from item in items
where item.Active
select item;
return (List<MyType>)selectedItems;
gives warning :
Suspicious cast: there is no type in the solution which inherits from both System.Linq.IOrderedEnumerable<MyType> and System.Collections.Generic.List<MyType>
What is best practice here
Simply use the ToList
extension:
return selectedItems.ToList();
You should be aware though: best practice (since you asked) would actually want you to return an IEnumerable<MyType>
in most cases. Therefore, you may want to change your signature in this way:
public IEnumerable<MyType> MyFunction()
{
// your code here
}
And THEN, if you need to, have the function's result in a list:
var myList = MyFunction().ToList();
Unless you have a very precise reason of returning a List<>
type, I strongly suggest that you don't.
Hope that helps.
Use the System.Linq.Enumerable.ToList<T>()
extension:
selectedItems.ToList();
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