被Linq和分组困惑

时间:2014-07-17 18:34:20

标签: c# linq

我正在玩Entity Framework和Linq并试图向我学习一些新东西。现在我有一个问题,我很容易用SQL解决,但想用Linq来解决它。

我有一个Color类和一个Car类。每个Car对象都有一种颜色。

public class Color
{
    public int ColorID { get; set; }
    public string Name { get; set; }
}

public class Car
{
    public Guid CarID { get; set; }
    public string ModelName { get; set; }

    public int ColorID { get; set; }

    public virtual Color CarColor { get; set; }
}

现在我想创建一个查询来获取所有颜色(ID和名称)以及使用该颜色的汽车数量(如果有的话)。

这种尝试给了我几乎正确的结果,但它排除了未使用的颜色。

        var n3 = from car in db.Cars
                 join c in db.Colors on car.ColorID equals c.ColorID into j1
                 from j2 in j1.DefaultIfEmpty()
                 group j2 by j2.ColorID into colorgroup
                 select new ColorCarCount
                 {
                     CarCount = colorgroup.Count(t => t.ColorID != null),
                     ColorID = colorgroup.Key, //colorgroup.Key,
                     Name = colorgroup.FirstOrDefault().Name
                 };

这种尝试感觉最好,但在这里我无法获得颜色名称:

        var n4 = from c in db.Colors
                 join car in db.Cars on c.ColorID equals car.ColorID into j1
                 from j2 in j1.DefaultIfEmpty()
                 group j2 by j2.ColorID into colorgroup
                 select new ColorCarCount
                 {
                     CarCount = colorgroup.Count(t => t.ColorID != null),
                     ColorID = colorgroup.Key, 
                     Name = "Can't get color name here"
                 };

有什么建议吗?是的,我已经阅读了类似的问题,但我并没有真正理解 - 但我确信这很简单: - )

1 个答案:

答案 0 :(得分:3)

    var n4 = from c in db.Colors
             join car in db.Cars on c.ColorID equals car.ColorID into tmp
             from car in tmp.DefaultIfEmpty()
             group car by c into colorgroup
             select new ColorCarCount
             {
                 CarCount = colorgroup.Count(),
                 ColorID = colorgroup.Key.ColorID,
                 Name = colorgroup.Key.Name
             };