我看过这个主题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

我需要在“左连接”内部实现,我尝试过这样:

我的类(class):
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

我可以在“选择新的”之前放置一个简单的位置,但是我必须通过这种方式来实现,在左联接中使用“之间”。

最佳答案

编辑-添加了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
                   };

关于c# - Linq-等效于左联接中的BETWEEN,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7093506/

10-11 19:57