Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.List<string>

匿名 (未验证) 提交于 2019-12-03 08:28:06

问题:

I have the code below:

List aa = (from char c in source                    select new { Data = c.ToString() }).ToList(); 

But what about

List aa = (from char c1 in source                    from char c2 in source                    select new { Data = string.Concat(c1, ".", c2)).ToList(); 

While compile getting error

Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List'

Need help.

回答1:

IEnumerable e = (from char c in source                         select new { Data = c.ToString() }).Select(t = > t.Data); // or IEnumerable e = from char c in source                         select c.ToString(); // or IEnumerable e = source.Select(c = > c.ToString()); 

Then you can call ToList():

List l = (from char c in source                   select new { Data = c.ToString() }).Select(t = > t.Data).ToList(); // or List l = (from char c in source                   select c.ToString()).ToList(); // or List l = source.Select(c = > c.ToString()).ToList(); 


回答2:

If you want it to be List, get rid of the anonymous type and add a .ToList() call:

List list = (from char c in source                      select c.ToString()).ToList(); 


回答3:

try

var lst= (from char c in source select c.ToString()).ToList(); 


回答4:

If you have source as a string like "abcd" and want to produce a list like this:

{ "a.a" }, { "b.b" }, { "c.c" }, { "d.d" } 

then call:

List list = source.Select(c => String.Concat(c, ".", c)).ToList(); 


回答5:

I think the answers are below

List aa = (from char c in source                     select c.ToString() ).ToList();  List aa2 = (from char c1 in source                     from char c2 in source                     select string.Concat(c1, ".", c2)).ToList(); 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!