linq 无法将类型“System.Collections.Generic.IEnumerable&lt;AnonymousType#1&gt;”隐式转换为“System.Collections.Generic.List< string>

e3bfsja2  于 2023-09-28  发布在  其他
关注(0)|答案(5)|浏览(196)

我有下面的代码:

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

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

编译时出错
无法将类型'System.Collections.Generic.List<AnonymousType#1>'隐式转换为'System.Collections.Generic.List<string>'
需要帮助

z9ju0rcb

z9ju0rcb1#

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

然后你可以调用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();
62lalag4

62lalag42#

如果你希望它是List<string>,去掉匿名类型,添加一个.ToList()调用:

List<string> list = (from char c in source
                     select c.ToString()).ToList();
zujrkrfu

zujrkrfu3#

尝试

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

m528fe3b4#

如果你有一个像"abcd"这样的字符串source,并想生成一个像这样的列表:

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

然后呼叫:

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

mzmfm0qo5#

我想答案在下面

List<string> aa = (from char c in source
                    select c.ToString() ).ToList();

List<string> aa2 = (from char c1 in source
                    from char c2 in source
                    select string.Concat(c1, ".", c2)).ToList();

相关问题