juergen d
juergen d

Reputation: 204854

IList does not contain a definition <linq function>

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?

Upvotes: 11

Views: 4009

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460228

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();

Upvotes: 10

juergen d
juergen d

Reputation: 204854

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.

Upvotes: 6

Related Questions