如何获得第一条记录使用LINQ每组 [英] How to get first record in each group using Linq

查看:110
本文介绍了如何获得第一条记录使用LINQ每组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下记录:

 标识F1 F2 F3 
---------- ---------------------------------------
1尼玛1990年10
2尼玛1990年11
3尼玛2000 12
4约翰·2001年1
5约翰·2002年2
6萨拉·2010年4月

我要组由根据 F1 字段排序标识并从一批类似这些记录的第一个记录的所有字段:

 标识F1 F2 F3 
----------------------------------------------- -
1尼玛1990年10
4约翰·2001年1
6萨拉·2010年4月

我怎样才能做到这一点使用LINQ?


解决方案

  VAR解析度=从列表
族元素的元素通过element.F1
到组
选择groups.OrderBy(p => p.F2)。首先();


Considering the following records:

   Id          F1            F2             F3 
 -------------------------------------------------
   1           Nima          1990           10
   2           Nima          1990           11
   3           Nima          2000           12
   4           John          2001           1
   5           John          2002           2 
   6           Sara          2010           4

I want to group by based on the F1 field and sort by Id and get all fields from the first record of group similar to these records:

   Id          F1            F2             F3 
 -------------------------------------------------
   1           Nima          1990           10
   4           John          2001           1
   6           Sara          2010           4

How I can do this using linq?

解决方案

    var res = from element in list
              group element by element.F1
                  into groups
                  select groups.OrderBy(p => p.F2).First();

这篇关于如何获得第一条记录使用LINQ每组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆