我有以下代码:
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>'
需要帮助。
答案 0 :(得分: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());
然后你可以拨打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();
答案 1 :(得分:11)
如果您希望它为List<string>
,请删除匿名类型并添加.ToList()
来电:
List<string> list = (from char c in source
select c.ToString()).ToList();
答案 2 :(得分:2)
试
var lst= (from char c in source select c.ToString()).ToList();
答案 3 :(得分:2)
如果您将源代码作为"abcd"
之类的字符串,并希望生成如下列表:
{ "a.a" },
{ "b.b" },
{ "c.c" },
{ "d.d" }
然后致电:
List<string> list = source.Select(c => String.Concat(c, ".", c)).ToList();
答案 4 :(得分:1)
我认为答案在下面
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();