在C#中使用linq查询和获取最后修改日期记录的数据表 [英] Datatable to query and fetch lastmodified date records using linq in C#
问题描述
数据表需要使用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外,
LINQOrderByDescending
和Distinct
方法。如您想要 Id 的唯一记录,首先需要按Id分组记录,在其上应用distinct,然后对其进行排序。
In addition to the Solution #1,
LINQ hasOrderByDescending
andDistinct
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 anIEnumerable
so that you can use linq. ThenGroupBy
theid
column. Use theresultSelector
function that's passed to theGroupBy
statement to select an anonymous type that contains the most recentDateTime
in the group. Use thevalues
parameter and theOrderByDecending
,Select
andFirst
statements to do this. In a lambda expression, you can reference a column field in aDataRow
like this.
dr.Field<string>("id")
如果您遇到困难,请发布您的代码,我会尽力帮助您。
If you get stuck, post your code and I will try to help you.
这篇关于在C#中使用linq查询和获取最后修改日期记录的数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!