16

我有以下课程:

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

4 回答 4

31

制作您的字段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
};
于 2013-08-28T17:18:25.130 回答
10

只是对我的评论的更全面的跟进。您要做的是使用对象初始化,这需要您命名属性。它认为您正在尝试的是集合初始化

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
                };
于 2013-08-28T17:16:47.097 回答
9

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

select new CommentList
{
    ItemType = d.ItemType,
    Comment1 = c.Comment1,
    Status1 = s.Status1,
    DiscussionBoardId = c.DiscussionBoardId,
    CourseId = d.CourseId,
    CommentID = c.CommentID
};
于 2013-08-28T17:16:07.453 回答
3

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

您需要明确分配您的属性:

new CommentList {
    ItemType = d.ItemType, 
    ...
于 2013-08-28T17:16:15.360 回答