[英]Find a value from Datatable compare with its max() value - LINQ Query
[英]Linq Query to find min and max in a datatable
我正在數據表中獲取員工的出勤詳細信息。 看起來像這樣
Day SwipeTime
12/31/2012 11AM
12/31/2012 1PM
12/31/2012 7PM
12/31/2012 8PM
1/1/2012 2PM
1/1/2012 7PM
1/1/2012 8PM
1/2/2012 10AM
1/2/2012 8PM
我需要顯示員工的日期和總時數,其中總時數= lastswipe-firstwipe
我的結果看起來像
Day TotalHours
12/31/2012 9
1/1/2012 6
1/2/2012 12
所以我需要找到按日期分組的最小和最大滑動次數。 請幫我寫查詢
您可以使用Enumerable.GroupBy
按date
分組。 然后,您可以創建一個Dictionary<DateTime,int>
,其中鍵是日期,值是該日期的總時數:
Dictionary<DateTime,int> dateGroups = table.AsEnumerable()
.GroupBy(r => r.Field<DateTime>("Date").Date)
.Select(g => new{
Date = g.Key,
TotalHours = g.Sum(r =>
DateTime.ParseExact(r.Field<string>("SwipeTime"),
"htt", CultureInfo.InvariantCulture).Hour)
}).ToDictionary(x => x.Date, x => x.TotalHours);
編輯 :所以,那是一TotalHours
,現在是所需的最大-最小計算。 您還已將所需的時間跨度格式更改為“ 11:41 AM”。 然后,我將使用DateTime.Parse(str).TimeOfDay
來獲取時間跨度。
Dictionary<DateTime, int> dateGroups = table.AsEnumerable()
.GroupBy(r => r.Field<DateTime>("Date").Date)
.Select(g => new
{
Date = g.Key,
TotalHours =
(g.Max(r => DateTime.Parse(r.Field<string>("SwipeTime")).TimeOfDay)
- g.Min(r => DateTime.Parse(r.Field<string>("SwipeTime")).TimeOfDay)).Hours
}).ToDictionary(x => x.Date, x => x.TotalHours);
在此答案中,創建一天的有序時間表以避免兩種情況-兩次解析所有行,並從解析后的值創建兩組以獲取最大和最小項。 另外,我不會在分組前解析日期,因為同一日期將具有相同的字符串值。
var query = from row in table.AsEnumerable()
group row by row.Field<string>("Day") into g
let times = g.Select(r => DateTime.Parse(r.Field<string>("SwipeTime")))
.OrderBy(t => t.TimeOfDay)
.ToList()
select new
{
DateTime.Parse(g.Key).Date,
(times.Last() - times.First()).TotalHours
};
結果是具有兩個屬性DateTime Date
和double TotalHours
的匿名對象的集合
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.