I have a IList
IList list = GetList();
and want to use Linq function on it like FirstOrDefault()
or Where()
but it says:
IList does not contain a definition for [linq function]
What am I doing wrong?
If your collection does not implement the generic interfaces you can use the Cast
or OfType
(Cast + Filter) extension methods.
IList list = GetList();
string first = list.Cast<string>().FirstOrDefault();
You can use these methods with anything that implements IEnumerable
. Of course it works only if the list really contains strings. If it could contain anything you could use:
string first = list.Cast<Object>().Select(obj => obj?.ToString() ?? "").FirstOrDefault();
If you just want objects that are strings you can use OfType
as mentioned above:
string first = list.OfType<string>().FirstOrDefault();
Make sure you are using the generic IList
with the type you use like this
IList<string> list = GetList();
Then you can use LINQ functions on that list.
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