Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用linq获取组中的最后一个数据_C#_Linq_Group By - Fatal编程技术网

C# 如何使用linq获取组中的最后一个数据

C# 如何使用linq获取组中的最后一个数据,c#,linq,group-by,C#,Linq,Group By,在我的表中,我有一个属性详细信息。每个属性都有代理名称。我想按代理名称分组,并获取每个代理最后插入的行。我使用了下面的代码,但它给出了第一行的值。当我使用lastordefault时,它显示错误。有人知道吗 var property = (from n in properties select n).GroupBy(x => x.agentname) .Where(g => g.Count() == 1) .Select(g

在我的表中,我有一个属性详细信息。每个属性都有代理名称。我想按代理名称分组,并获取每个代理最后插入的行。我使用了下面的代码,但它给出了第一行的值。当我使用lastordefault时,它显示错误。有人知道吗

 var property = (from n in properties select n).GroupBy(x => x.agentname)
              .Where(g => g.Count() == 1)
              .Select(g => g.FirstOrDefault()).OrderByDescending(x => x.datecreated).Take(20);

首先,您的第一个查询对我来说毫无意义,即
(从属性中的n选择n)
您可以直接在
属性上应用
GroupBy
。接下来,您将从组中选择第一条记录,并对完成的结果应用
OrderByDescending
,因为您只有一条记录,所以这不会起任何作用

这将给您带来预期的结果:-

var property = properties.GroupBy(x => x.agentname)
                         .Select(x => x.OrderByDescending(z => z.datecreated)
                                       .FirstOrDefault());

这将返回一个集合,其中包含每个代理的
最后插入的行

。其中(g=>g.Count()==1)
生成一条记录我们如何在中获取日期orderbydescnding@RahulSingh
GroupBy
之后没有
x.datecreated
(x是
i分组
):)@IvanStoev,OP-是的,我的错!更正thnx.@r.vengadesh-你有机会看看我的答案吗?