【问题标题】:Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.List<string>无法将类型 'System.Collections.Generic.IEnumerable<AnonymousType#1>' 隐式转换为 'System.Collections.Generic.List<string>
【发布时间】:2011-05-14 11:14:46
【问题描述】:

我有以下代码:

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&lt;AnonymousType#1&gt;' 隐式转换为 'System.Collections.Generic.List&lt;string&gt;'

需要帮助。

【问题讨论】:

  • 最后的任务是什么,来源是什么?
  • 至于您上次编辑两次提到同一来源,请参阅我的回答 #2 - 它可以帮助您。

标签: c# .net linq compiler-errors


【解决方案1】:
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();

【讨论】:

  • @priyanka.sarkar_2:您应该使用Select(x =&gt; x.Data).ToList() 选择此类数据的列表。
【解决方案2】:

如果您希望它是 List&lt;string&gt;,请去掉匿名类型并添加 .ToList() 调用:

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

【讨论】:

  • List aa = (from char c1 in source from char c2 in source select new { Data = string.Concat(c1, ".", c2)).ToList ();
【解决方案3】:

试试

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

【讨论】:

  • 我不能使用 var.. 它必须是 List 由于某种原因
  • 这样你会得到List&lt;AnonymousType#1&gt;
  • @Rover:不,它没有,.ToList() 将 IEnumerable 变成 List
【解决方案4】:

如果您有像 "abcd" 这样的字符串形式的源并且想要生成这样的列表:

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

然后调用:

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

【讨论】:

    【解决方案5】:

    我认为答案如下

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

    【讨论】:

      猜你喜欢
      • 2013-05-14
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多