简体   繁体   English

在具有内部联接的LINQ查询中选择最新日期

[英]Select the most recent date in a LINQ query with an inner join

I have a LINQ query that queries two tables, and returns records successfully. 我有一个LINQ查询,查询两个表,并成功返回记录。 I want it to only return the most recent record, but I'm having trouble getting it to work. 我希望它只返回最近的记录,但是我无法使其正常工作。 It returns all of the records without an error. 它返回所有记录,没有错误。

My query is: 我的查询是:

  var viewModel = from area in db.area
                  join sample in db.sample on area.location_id equals sample.location_id
                  from s in db.sample.OrderByDescending(s => s.sample_date).Take(1)

                  select new AreaViewModel { h_area = area, s_sample = sample };

                  return View(viewModel);

Totally stuck, help greatly appreciated! 完全卡住,不胜感激!

You are calling Take() method at wrong place, you have to write something like: 您在错误的地方调用Take()方法,您必须编写类似以下内容的内容:

var viewModel = (from area in db.area
                 join sample in db.sample on area.location_id equals sample.location_id
                 from s in db.sample
                 select new AreaViewModel 
                       { 
                         h_area = area, 
                         s_sample = sample 
                       }).OrderByDescending(s => s.s_sample.sample_date)
                         .FirstOrDefault();

if you want to return collection, then you can use Take(1) there instead of FirstOrDefault() , as it will not return collection. 如果要返回收集,则可以在FirstOrDefault()使用Take(1)而不是FirstOrDefault() ,因为它不会返回收集。

I think what you are trying to achieve is this: 我认为您要实现的目标是:

var area= (from area in db.area
           join sample in db.sample on area.location_id equals sample.location_id
           orderby sample.sample_date descending
           select new AreaViewModel { h_area = area, s_sample = sample }).FirstOrDefault();

Calling FirstOrDefault method you will get the most recent record due to it adds TOP(1) to the SQL query that is generated by your Linq query. 调用FirstOrDefault方法将获得最新记录,这是因为它将TOP(1)添加到Linq查询生成的SQL查询中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM