Linq查询返回列表中的列表

时间:2014-04-21 12:02:02

标签: c# linq lambda

您好我有以下两个模型类

public class c1
{
    public int id { get; set; }
    public int ptId { get; set; }
    public int bId { get; set; }
    public int rId { get; set; }
    public IEnumerable<styles> newStruct { get; set; }
}

public class styles
{
    public int id { get; set; }
    public int bId { get; set; }
    public string desc { get; set; }
}

我正在尝试编写一个linq查询

var records = (from y in db.main
               join c in db.secondary on y.bId equals c.bId
               where c.id == id
               select new c1
               {
                   pId= c.pId,
                   id = c.id,
                   newStruct = new List<styles>
                   {
                       new styles
                       {
                           id=y.room_id,
                           desc=y.desc,
                       }
                   }
               });

return records.ToList();

我遇到的问题是,在newStruct中假设是所有样式的List,但它只返回一个样式而不是一个列表。 请让我知道它如何返回记录里面的样式列表 感谢

2 个答案:

答案 0 :(得分:3)

如果您想通过主列表获取子列表,则应使用group by

你可以试试这个,但我不确定它是否奏效。 Becasue我无法编译它。

var records = (from y in db.main
                           join c in db.secondary on y.bId equals c.bId
                           where c.id == id
                           group c by new
                           {
                               c.pId,
                               c.id
                           } into gcs
                           select new c1
                           {
                               pId = c.Key.pId,
                               id = c.Key.id,
                               newStruct = from g in gcs select new styles { id=g.room_id, desc=g.desc}
                           });

答案 1 :(得分:0)

这是LINQ to Entities吗?如果是这样,并且edmx中的映射是正确的,您可以尝试:

var records = 
    from c in db.secondary
    where c.id == id
    select new c1
    {
        pId = c.pId,
        id = c.id,
        newStruct = c.main.Select(m => new styles { id = m.room_id, desc = m.desc })
    };

return records.ToList();