Linq - 相当于左连接中的BETWEEN

时间:2011-08-17 13:16:16

标签: c# linq

我已经看过这个话题BETWEEN EQUIVALENT in LINQ

我在SQL中的原始查询:

SELECT ISNULL(Tcar.name, '') FROM dbo.models model
LEFT JOIN cars Tcar on Tcar.model = model.id AND
                     Tcar.year between model.Start and model.End

我需要在“左连接”内部之间实现,我试过这个:

我的课程:

public class car
{
    public string name { get; set; }
    public int model { get; set; }
    public DateTime year { get; set; }
}

public class model
{
    public int id { get; set; }
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
}

我的实施:

var theModel = from model in models
               join Tcar in cars
                    on new
                        {
                            ID = (int)model.id,
                            DateStart = (DateTime)model.Start,
                            DateEnd = (DateTime)model.End
                        }
                     equals new                                 
                         {
                             ID = (int)Tcar.model,
                             DateStart = (DateTime)Tcar.year,
                             DateEnd = (DateTime)Tcar.year
                         } into tempCar
                       from finalCar in tempCar
               select new
                   {
                       CAR = (finalCar == null ? String.Empty : finalCar.name)
                   };

解决方法:

var theModel = from model in models
               join Tcar in cars
                    on model.id equals Tcar.model
                where model.Start <= Tcar.year && model.End >= Tcar.year
               select new
                   {
                       CAR = Tcar.name
                   };

如果我使用解决方法Linq翻译为此查询:

SELECT Tcar.name FROM dbo.models model
LEFT JOIN cars Tcar on Tcar.model == model.id
WHERE model.Start <= Tcar.year and model.End >= Tcar.year

我可以在“select new”之前放一个简单的地方,但是我必须通过这种方式实现,在左边的join中有“between”,我该怎么做?

2 个答案:

答案 0 :(得分:5)

编辑 - 添加DefaultOrEmpty()以使其成为左连接

像这样修改你的查询,这将强制where子句进入join on子句。它不会在Join中给你Between子句,但至少不会有where子句

var theModel = from model in models
               from Tcar in cars.Where(x => model.id == x.model)
                                .Where(x => model.Start <= x.year && model.End >= x.year)
                                .DefaultOrEmpty()
               select new
                   {
                       CAR = Tcar.name
                   };

答案 1 :(得分:2)

SQL Server应该考虑您的原始查询和LINQ生成的示例是相同的,因为WHERE model.Start <= Tcar.year and model.End >= Tcar.yearON Tcar.year between model.Start and model.End都指定了连接条件。

通常首选使用ON,因为它会使您的加入条件与其他搜索条件分开,但这是为了提高可读性而非性能。在我躺着的几张桌子上测试类似的查询会产生相同的查询计划,如果您看到不同的桌面计划,我会感到惊讶。