简体   繁体   English

Linq to Sql选择联接表中的最后一行

[英]Linq to Sql selecting last row in a joined table

I am trying to select multiple table values using linq to sql 我正在尝试使用linq to sql选择多个表值

This is the code I wrote: 这是我写的代码:

var query = (from p in context.Personel
join y in context.PerLanguage on p.ID equals y.ID
where p.Resign == false && p.KGBT > new DateTime(2012,1,15)
select new{ p.ID,p.NameSurname, y.EarnedDate,y.Degree}).ToList();

PerLanguage has a foreignkey "ID" to Personel. PerLanguage具有一个指向Personel的外键“ ID”。 So PerLanguage table can have 2 or more data that has the same ID. 因此,PerLanguage表可以包含2个或多个具有相同ID的数据。 I am expecting this piece of code to return me a List of items having the "last" entered Language data of different people. 我希望这段代码可以返回一个列表,其中包含“最后”输入的不同人的语言数据。

What is the best way to do it? 最好的方法是什么?

try the following query.. basically we make the join, get the flat results, group it by id and descending sort the results within an ID and select the first record in every grouped result. 尝试以下查询..基本上,我们进行联接,获得固定结果,按ID分组并在ID中对结果进行降序排序,并在每个分组结果中选择第一条记录。

var results = context.Personel.Where(p => !p.Resign && p.KGBT > new 
DateTime(2012,1,15)).Join(context.PerLanguage, p => p.ID, pl => pl.ID, (p, pl) => 
new { p.ID, p.NameSurname, pl.EarnedDate, pl.Degree }).GroupBy(r => r.ID)
.Select(g => g.OrderByDescending(r => r.EarnedDate).First()).ToList();

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

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