C# 获取日期最高的最新记录和组-LINQ
我有如下表C# 获取日期最高的最新记录和组-LINQ,c#,linq,C#,Linq,我有如下表账单 AccoundID | Group | DateOfBill 1234 | A | 2017-07-12 1234 | B | 2017-07-16 1234 | C | 2017-07-31 1235 | A | 2017-07-31 1236 | B | 2017-07-31 如您所见,AccountID1234在2017年7月进行了3笔交易。因此,我需要一个列表,其中AccountI
账单
AccoundID | Group | DateOfBill
1234 | A | 2017-07-12
1234 | B | 2017-07-16
1234 | C | 2017-07-31
1235 | A | 2017-07-31
1236 | B | 2017-07-31
如您所见,AccountID
1234在2017年7月进行了3笔交易。因此,我需要一个列表,其中AccountID
1234必须位于组
C中,因为这是该交易的最新日期
这是我的代码片段
var LatestAccount = from n in Billing
where (n.Group == "A" || n.Group == "B" || n.Group == "C")
group n by new { n.AccountID, n.Group } into g
select new {
AccountId = g.Key.AccountID,
Group = g.Key.Group ,
DateOfBill = g.Max(t => t.DateOfBill)
};
但结果是错误的。在LINQ中如何做?类程序
class Program
{
static void Main(string[] args)
{
List<Billing> Billings = new List<Billing>()
{
new Billing()
{
AccountID = 1234, DateOfBill = new DateTime(2017,07,12), Group = "A"
},
new Billing()
{
AccountID = 1234, DateOfBill = new DateTime(2017,07,16), Group = "B"
},
new Billing()
{
AccountID = 1234, DateOfBill = new DateTime(2017,07,31), Group = "C"
},
new Billing()
{
AccountID = 1235, DateOfBill = new DateTime(2017,07,31), Group = "A"
},
new Billing()
{
AccountID = 1236, DateOfBill = new DateTime(2017,07,31), Group = "B"
}
};
var LatestAccount = from n in Billings
where (n.Group == "A" || n.Group == "B" || n.Group == "C")
group n by new { n.AccountID } into g
select g.Where(d => d.DateOfBill == g.Max(m => m.DateOfBill)).Select(x => new { AccountId = g.Key.AccountID, Group = x.Group, DateOfBill = x.DateOfBill }).FirstOrDefault();
foreach (var item in LatestAccount)
{
Console.WriteLine("AccountID: " + item.AccountId + " Date of Bill: " + item.DateOfBill + " Group: "+ item.Group);
}
Console.ReadLine();
}
}
class Billing
{
public int AccountID { get; set; }
public string Group { get; set; }
public DateTime DateOfBill { get; set; }
}
{
静态void Main(字符串[]参数)
{
列表账单=新列表()
{
新帐单()
{
AccountID=1234,DateOfBill=new DateTime(2017,07,12),Group=“A”
},
新帐单()
{
AccountID=1234,DateOfBill=new DateTime(2017,07,16),Group=“B”
},
新帐单()
{
AccountID=1234,DateOfBill=new DateTime(2017,07,31),Group=“C”
},
新帐单()
{
AccountID=1235,DateOfBill=new DateTime(2017,07,31),Group=“A”
},
新帐单()
{
AccountID=1236,DateOfBill=new DateTime(2017,07,31),Group=“B”
}
};
var LatestAccount=从n开始,单位为账单
其中(n.Group==“A”| n.Group==“B”| n.Group==“C”)
将n按新的{n.AccountID}分组到g中
选择g.Where(d=>d.DateOfBill==g.Max(m=>m.DateOfBill)).select(x=>new{AccountId=g.Key.AccountId,Group=x.Group,DateOfBill=x.DateOfBill}.FirstOrDefault();
foreach(LatestAccount中的var项目)
{
Console.WriteLine(“AccountID:+item.AccountID+”票据日期:+item.DateOfBill+”组:+item.Group);
}
Console.ReadLine();
}
}
分类计费
{
public int AccountID{get;set;}
公共字符串组{get;set;}
public DateTime DateOfBill{get;set;}
}
低于你想要的吗?
如果你给我看你想要的输出,我可以修改我的答案
您正在按帐户Id和组进行分组。你想在你的用例中只按帐户Id分组,为什么不发布最终结果应该是什么样子?是的,这正是我想要的。如果我的回答对你有效,请接受我的回答作为正确答案-这样其他用户可以受益:知道答案有效,并将问题标记为已回答。请让我知道我的答案是否对您有效,或者您对答案是否有任何问题。