我有Capsule::getQueryLog()
表格,如下所示
Billing
如您所见,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
1234在2017年7月进行了3次交易。所以我需要一个AccountID
1234必须在AccountID
C的列表,因为那是最新日期事务。
这是我的代码段
Group
但结果是错误的。怎么做LINQ?
答案 0 :(得分:2)
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; }
}
低于你想要的? 如果你告诉我你想要的输出,我可以修改我的答案。