被Linq和分组弄糊涂了

本文关键字:弄糊涂 Linq | 更新日期: 2023-09-27 18:13:19

我正在玩实体框架和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"
                 };

有什么建议吗?是的,我读过类似的问题,但我不太明白-但我相信这很容易:-)

被Linq和分组弄糊涂了

    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
             };