【问题标题】:Cannot initialize type 'class' with a collection initializer because it does not implement 'IEnumerable'无法使用集合初始化程序初始化类型“类”,因为它没有实现“IEnumerable”
【发布时间】:2010-07-20 15:24:14
【问题描述】:

谁能告诉我为什么这不起作用?

 public class GeocodeCoord
 {
     public string Outcode { get; set; }
     public int X { get; set; }
     public int Y { get; set; }
 }

List<GeocodeCoord> _geocode;

using (MyDataContext db = new MyDataContext())
{
   _geocode = db.Geocodes.Select(g => new GeocodeCoord { g.postcode, g.x, g.y }).ToList<GeocodeCoord>();
}

我收到以下错误:

无法使用集合初始化程序初始化类型“Search.GeocodeCoord”,因为它没有实现“System.Collections.IEnumerable”

【问题讨论】:

  • 什么不起作用?你有例外吗?您是否收到编译时错误?
  • 我得到一个编译器错误,刚刚添加了额外的信息......干杯

标签: linq linq-to-sql


【解决方案1】:

该行应该是:

_geocode = db.Geocodes.Select(g => new GeocodeCoord { Outcode = g.postcode, X = g.x, Y = g.y }).ToList();

【讨论】:

  • 漂亮!!非常感谢你 :).. 刚试了一下,效果很好 :)
【解决方案2】:

只要使用ToList(),编译器就会为你找到正确的类型。

【讨论】:

  • 如果我这样做 _geocode = db.Geocodes.Select(g => new GeocodeCoord { g.postcode, g.x, g.y }).ToList();我犯了同样的错误。如果我执行以下操作:_geocode = db.Geocodes.Select(g => new { g.postcode, g.x, g.y }).ToList();我无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List
【解决方案3】:

输入初始化器的属性名称,如new GeocodeCoord { Postcode = g.postcode, X = g.x, Y = g.y }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    相关资源
    最近更新 更多