我有一张如下表
Name Entrytime Exittime
A 10:30 AM 6:30PM
A 7:30 AM 5:30PM
B 10:30 AM 2:30PM
A 5:30 AM 3:30PM
B 11:30 AM 4:30PM
A 8:30 AM 7:30PM
C 9:30 AM 1:30PM
C 10:30 AM 9:30PM
我需要使用linq查询获取每个名称的最小录入时间和每个名称的最长退出时间
所以我需要像下面的结果集
Name Entrytime Exittime
A 5:30 AM 7:30PM
B 10:30 AM 4:30PM
C 9:30 AM 9:30PM
答案 0 :(得分:2)
Table
.GroupBy(x=>x.Name)
.Select(x=>new {Name=x.Key,
Entrytime=x.Min(m=>m.Entrytime),
Exittime=x.Max(m=>m.Exittime)})
这是一个LinqPad查询,显示当入口时间和退出时间是字符串而不是日期时间时,如何在IEnumerable上执行此操作:
var list= new[]{
new {Name="A",Entrytime="10:30 AM",Exittime="6:30PM"},
new {Name="A",Entrytime="7:30 AM",Exittime="5:30PM"},
new {Name="B",Entrytime="10:30 AM",Exittime="2:30PM"},
new {Name="A",Entrytime="5:30 AM",Exittime="3:30PM"},
new {Name="B",Entrytime="11:30 AM",Exittime="4:30PM"},
new {Name="A",Entrytime="8:30 AM",Exittime="7:30PM"},
new {Name="C",Entrytime="9:30 AM",Exittime="1:30PM"},
new {Name="C",Entrytime="10:30 AM",Exittime="9:30PM"}};
var result=list.GroupBy(x=>x.Name)
.Select(x=>new {Name=x.Key,
Entrytime=x.Min(m=>DateTime.Parse(m.Entrytime)).ToString("h:mm tt"),
Exittime=x.Max(m=>DateTime.Parse(m.Exittime)).ToString("h:mm tt")});
result.Dump();
答案 1 :(得分:0)
from t in table
group t by t.name into tgroup
select new
{
name = tgroup.Key,
entrytime = tgroup.Min(x => x.entrytime),
exittime = tgroup.Max(x => x.exittime)
}