我对此有些困惑。基本上,我想在LINQ to SQL中执行以下SQL查询:
SELECT *
FROM UnitPrice
WHERE EffectiveDateTime = (SELECT MAX(EffectiveDateTime)
FROM UnitPrice AS InnerUnitPrice
WHERE InnerUnitPrice.EffectiveDateTime < GETDATE())
答案 0 :(得分:1)
您可以执行以下操作。
使用DataTable模拟您的场景
var unitPrice = new DataTable();
unitPrice.Columns.Add("EffectiveDateTime",typeof(DateTime));
unitPrice.Columns.Add("SomeOther",typeof(string));
unitPrice.Rows.Add(new DateTime(2018,12,1), "Sample1");
unitPrice.Rows.Add(new DateTime(2018,12,2), "Sample2");
unitPrice.Rows.Add(new DateTime(2018,12,3), "Sample3");
unitPrice.Rows.Add(new DateTime(2018,12,4), "Sample41");
unitPrice.Rows.Add(new DateTime(2018,12,4), "Sample4");
unitPrice.Rows.Add(new DateTime(2019,12,4), "Sample5");
您可以查询所需结果,
var result = unitPrice.AsEnumerable()
.Where(x=>x.Field<DateTime>("EffectiveDateTime") < DateTime.Today)
.GroupBy(x=>x.Field<DateTime>("EffectiveDateTime"))
.OrderByDescending(x=>x.Key)
.First().ToList();
输出
04-12-2018 00:00:00 Sample41
04-12-2018 00:00:00 Sample4
答案 1 :(得分:0)
在这个简短的对象列表上,我举一个例子
List < Entry > list = new List<Entry>();
list.Add(new Entry("a","_a",new DateTime(2019,1,30),1));
list.Add(new Entry("b", "_b", new DateTime(2018, 12, 31), 2));
list.Add(new Entry("c", "_c", new DateTime(2018, 12, 31), 3));
list.Add(new Entry("d", "_d", new DateTime(2018, 12, 30), 4));
list.Add(new Entry("e", "_e", new DateTime(2018, 11, 30), 5));
Entry类的属性依次为引用(字符串),捐赠(字符串),日期(日期时间),金额(两倍)。
第一步,我们要选择今天之前的最新日期(您在子查询中执行的操作);从我们的列表开始,我们可以做这样的事情:
var max_date = from l in list
where l.Date < DateTime.Today
group l.Date by 1 into g
select new { Val=g.Max() };
foreach (var m in max_date)
{
Console.WriteLine(m.Val);
}
运行此功能,您将获得所需的31/12/2018。但是,我们需要另一步骤来选择所选日期的所有信息。因此,在第2步中,我们将开始列表与刚刚构建的列表进行内部连接:
var list2 = from l in list
join m in max_date on l.Date equals m.Val
select l;
foreach (var l in list2)
{
Console.WriteLine($"{l.Reference}, {l.Donation}, {l.Date}, {l.Amount}");
}
结果将是
b, _b, 31/12/2018 00:00:00, 2
c, _c, 31/12/2018 00:00:00, 3
根据需要。希望对您有帮助!
答案 2 :(得分:0)
Linq lamda查询:
var q = db.UnitPrice
.Where(x1 => x1.EffectiveDateTime == db.UnitPrice
.Where(x2 => x2.EffectiveDateTime < DateTime.Now)
.Max(x3 => x3.EffectiveDateTime)
)
.ToList();