Linq - 相当于左连接中的BETWEEN

Gan*_*rez 6 c# linq

在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
Run Code Online (Sandbox Code Playgroud)

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

我的课程:

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; }
}
Run Code Online (Sandbox Code Playgroud)

我的实施:

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)
                   };
Run Code Online (Sandbox Code Playgroud)

解决方法:

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
                   };
Run Code Online (Sandbox Code Playgroud)

如果我使用解决方法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
Run Code Online (Sandbox Code Playgroud)

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

Adu*_*cci 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
                   };
Run Code Online (Sandbox Code Playgroud)

  • @Jon Skeet - 我使用的是Gandarez在他的例子中使用的匿名类型.我觉得使用double*from*with multiple*Where*语句,最后使用*DefaultOrEmpty*是在Linq中编写左连接的最可读方式.并且生成的sql将加入critera放在*ON*而不是*Where*语句中 (2认同)