无法使用集合初始值设定项实现XYZ类型,因为它没有实现'System.Collections.IEnumerable'

时间:2013-08-28 17:14:22

标签: c# asp.net linq collections

我有以下课程:

public class CommentList 
{
    string ItemType;
    string Comment1;
    string Status1;
    string DiscussionBoardId;
    Guid CourseId;
    Guid CommentID;
}

我正在尝试执行以下LINQ语句:

List<CommentList> query=
    from c in db.Comments
    join s in db.Status on c.StatusId equals s.StatusId
    join d in db.DiscussionBoards 
        on c.DiscussionBoardId equals d.DiscussionBoardId
    where d.CourseId=="CourseID"
    orderby d.ItemType, d.DiscussionBoardId
    select new CommentList {
        d.ItemType,
        c.Comment1,
        s.Status1,
        c.DiscussionBoardId,
        d.CourseId,
        c.CommentID
    };

问题是,编辑器抱怨select语句的第一个括号。它说:

  

无法使用集合初始值设定项实现类型'CommentList',因为它没有实现'System.Collections.IEnumerable'。

有人可以帮助我并告诉我我做错了什么吗?

4 个答案:

答案 0 :(得分:26)

制作字段public,因为它们现在无法访问。

public class CommentList
{
  public string ItemType;
  public string Comment1;
  public string Status1;
  public string DiscussionBoardId;
  public Guid CourseId;
  public Guid CommentID;
}

明确地将它们设置在初始化程序中。

select new CommentList
{
    ItemType = d.ItemType,
    Comment1 = c.Comment1,
    Status1 = s.Status1,
    DiscussionBoardId = c.DiscussionBoardId,
    CourseId = d.CourseId,
    CommentID = c.CommentID
};

答案 1 :(得分:8)

您的初始化不正确。您需要为显式属性赋值。

select new CommentList
{
    ItemType = d.ItemType,
    Comment1 = c.Comment1,
    Status1 = s.Status1,
    DiscussionBoardId = c.DiscussionBoardId,
    CourseId = d.CourseId,
    CommentID = c.CommentID
};

答案 2 :(得分:6)

对我的评论进行更全面的跟进。您要做的是use object initialization,它要求您命名属性。它认为你正在尝试的是collection initialization

List<CommentList> query = from c in db.Comments
                join s in db.Status on c.StatusId equals s.StatusId
                join d in db.DiscussionBoards on c.DiscussionBoardId equals d.DiscussionBoardId
                where d.CourseId == "CourseID"
                orderby d.ItemType, d.DiscussionBoardId
                select new CommentList
                {
                    ItemType = d.ItemType,
                    Comment1 = c.Comment1,
                    Status1= s.Status1,
                    DiscussionBoardId = c.DiscussionBoardId,
                    CourseId = d.CourseId,
                    CommentId = c.CommentID
                };

答案 3 :(得分:3)

您只能在创建匿名类型时推断属性名称。

您需要明确指定属性:

new CommentList {
    ItemType = d.ItemType, 
    ...