Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Convert IEnumerable to IList using .ToList()?

I am using an external library thats returns a IEnumerable. After I have recieved them I would like to add some models to the end. That only seems possible when using an IList or some other collection. So when i'm trying to convert the IEnumerable to a list using the .ToList() method it returns an IEnumerable. That's not the what I expected? Am I using .ToList() correct? Or what else would solve my problem?

This is my code i have so far:

IList<Models.Browser.Language> languages = GetLanguages(dateDrom, dateTo).ToList();
IList<Models.Browser.Language> primaryItems = languages.Take(10);

This last line produces an error saying: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<Bogus.Models.Browser.Language>' to 'System.Collections.Generic.IList<Bogus.Models.Browser.Language>'. An explicit conversion exists (are you missing a cast?)

Thanks in advance!

like image 282
mmmmm Avatar asked Nov 29 '22 09:11

mmmmm


1 Answers

The value of languages is a reference to a List<>, but then you're calling Take(10) on that, which doesn't return a list.

Just move your ToList() call:

IEnumerable<Models.Browser.Language> languages = GetLanguages(dateDrom, dateTo);
IList<Models.Browser.Language> primaryItems = languages.Take(10).ToList();

Or just do it in one call:

var primaryItems = GetLanguages(dateDrom, dateTo).Take(10).ToList();

Also, this isn't quite correct:

After I have recieved them I would like to add some models to the end.

An alternative is to use Concat. For example:

var items = GetLanguages(dateDrom, dateTo).Take(10).Concat(fixedItems);
like image 191
Jon Skeet Avatar answered Dec 15 '22 23:12

Jon Skeet