views:

223

answers:

3

Hi folks, new to LINQ & would like to know why the error & best way to resolve.

I am getting, 'Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)' error

List<string> names = new List<string>();
names.Add("audi a2");
names.Add("audi a4");

List<string> result1 = new List<string>();

result1=(from name in names
         where name.Contains("a2")
         select name);
+6  A: 

The result of the from is an IEnumerable, you need to create a list to hold it.

result1=(from name in names
                    where name.Contains("a2")
                    select name).ToList();

so you can simply:

List<string> result1 = (from name in names
                                 where name.Contains("a2")
                                 select name).ToList();
Preet Sangha
ah, very nice, thank you.
SoftwareGeek
+3  A: 

Throw on .ToList() at the end of your Linq query.

result1=(from name in names
     where name.Contains("a2")
     select name).ToList();
Corey Sunwold
+1  A: 

Or using Linq's function syntax:

result1 = names.where(x => x.Contains("a2")).ToList();
Obalix
do u read it as 'x goes to name.contains...'?
SoftwareGeek
read it as where (for each item (x) in names run the test x.Contains(...)
Preet Sangha
@preet - saw your profile, great sense of humor!
SoftwareGeek
@preed: oops, thank you ... it is too late ... :-)
Obalix
@ironically I'm a vegetarian....hahaha
Preet Sangha
@preet - LOL, good one.
SoftwareGeek
@Obalix - great answer, u did it in 1 line! that's pretty cool.
SoftwareGeek