简体   繁体   中英

C# - Linq to SQL , type conversion error

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

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

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

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

或者使用Linq的函数语法:

result1 = names.where(x => x.Contains("a2")).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM