在C#中使用linq查询和获取最后修改日期记录的数据表 [英] Datatable to query and fetch lastmodified date records using linq in C#

查看:622
本文介绍了在C#中使用linq查询和获取最后修改日期记录的数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据表需要使用linq查询并使用uniqueID获取最后修改日期记录。



输入:



Datatable need to queried and fetch last modified date record with uniqueID using linq.

Input:

id        Name     Depart     ModifiedDate
S123      vin       cse        2018-06-29 13:24:00.723
S124      sham      EEE        2018-06-29 13:24:00.724
S123      Vin       ECE        2018-06-29 13:25:00.000





我需要输出







I need output as


id        Name     Depart     ModifiedDate
S123      Vin       ECE        2018-06-29 13:25:00.000
S124      sham      EEE        2018-06-29 13:24:00.724





我尝试过:



我需要输出







What I have tried:

I need output as


id        Name     Depart     ModifiedDate
S123      Vin       ECE        2018-06-29 13:25:00.000
S124      sham      EEE        2018-06-29 13:24:00.724

推荐答案

这里有几个网页让你入门的页面



c# - 关于DataTable的LINQ查询 - 堆栈溢出 [ ^ ]

< a href =https://www.codeproject.com/Tips/834368/Working-with-LINQ-to-Entities-LINQ-to declaredTable>使用LINQ to Entities& LINQ to DataTable [ ^ ]
here are a couple of web pages to get you started

c# - LINQ query on a DataTable - Stack Overflow[^]
Working with LINQ to Entities & LINQ to DataTable[^]


除解决方案#1外,



LINQ OrderByDescending Distinct 方法。如您想要 Id 的唯一记录,首先需要按Id分组记录,在其上应用distinct,然后对其进行排序。

In addition to the Solution #1,

LINQ has OrderByDescending and Distinct methods. As you want unique records by Id, you first need to group the records by Id, apply distinct on it and then sort it.
var data = list.GroupBy(x => x.Id).Select(g => g.First()).ToList();
var datalist = data.Distinct().OrderByDescending(x => x.ModifiedDate);



这可能会解决您的问题,试一试!





KR


This might solve your problem, give it a try!


KR


首先,你需要隐藏你的 DataTable IEnumerable ,以便您可以使用linq。然后 GroupBy id 列。使用传递给 GroupBy 语句的 resultSelector 函数来选择包含最新<$ c $的匿名类型c>组中的DateTime 。使用参数和 OrderByDecending 选择第一个语句来执行此操作。在lambda表达式中,您可以像这样引用 DataRow 中的列字段。

First of all, you need to covert your DataTable to an IEnumerable so that you can use linq. Then GroupBy the id column. Use the resultSelector function that's passed to the GroupBy statement to select an anonymous type that contains the most recent DateTime in the group. Use the values parameter and the OrderByDecending, Select and First statements to do this. In a lambda expression, you can reference a column field in a DataRow like this.

dr.Field<string>("id")



如果您遇到困难,请发布您的代码,我会尽力帮助您。


If you get stuck, post your code and I will try to help you.


这篇关于在C#中使用linq查询和获取最后修改日期记录的数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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