Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IList does not contain a definition <linq function>

Tags:

c#

linq

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?

like image 835
juergen d Avatar asked Sep 06 '19 15:09

juergen d


2 Answers

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();
like image 184
Tim Schmelter Avatar answered Oct 27 '22 15:10

Tim Schmelter


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.

like image 30
juergen d Avatar answered Oct 27 '22 16:10

juergen d