无法将类型'System.Collections.Generic.IEnumerable <AnonymousType#1>'隐式转换为'System.Collections.Generic.List <string>

40 .net c# linq compiler-errors

我有以下代码:

List<string> aa = (from char c in source
                   select new { Data = c.ToString() }).ToList();
Run Code Online (Sandbox Code Playgroud)

但是关于

List<string> aa = (from char c1 in source
                   from char c2 in source
                   select new { Data = string.Concat(c1, ".", c2)).ToList<string>();
Run Code Online (Sandbox Code Playgroud)

编译时收到错误

无法隐式转换'System.Collections.Generic.List<AnonymousType#1>''System.Collections.Generic.List<string>'

需要帮忙.

aba*_*hev 49

IEnumerable<string> e = (from char c in source
                        select new { Data = c.ToString() }).Select(t = > t.Data);
// or
IEnumerable<string> e = from char c in source
                        select c.ToString();
// or
IEnumerable<string> e = source.Select(c = > c.ToString());
Run Code Online (Sandbox Code Playgroud)

然后你可以打电话ToList():

List<string> l = (from char c in source
                  select new { Data = c.ToString() }).Select(t = > t.Data).ToList();
// or
List<string> l = (from char c in source
                  select c.ToString()).ToList();
// or
List<string> l = source.Select(c = > c.ToString()).ToList();
Run Code Online (Sandbox Code Playgroud)

  • @ priyanka.sarkar_2:你应该使用`Select(x => x.Data).ToList()`来选择这样的数据列表. (2认同)

Jon*_*upp 11

如果你想要它List<string>,摆脱匿名类型并添加一个.ToList()电话:

List<string> list = (from char c in source
                     select c.ToString()).ToList();
Run Code Online (Sandbox Code Playgroud)