给定一个值列表,其中包含未知数量的不同字符串值,如何获取每个值的最新值?
我得到了一个具有以下三个属性的对象列表:余额、平衡类型和创建日期。 进入,我知道 BalanceType 可以设置为许多不同的值,但我不确定有多少个不同的值。例如,这是一个有效的输入:
[{
"BalanceType":"Cash",
"Balance":350.03,
"CreatedDate":10-20-16
},
{
"BalanceType":"Cash",
"Balance":250.01,
"CreatedDate":10-20-15
},
{
"BalanceType":"Cash",
"Balance":450.21,
"CreatedDate":10-20-14
},
{
"BalanceType":"Securiites",
"Balance":350.03,
"CreatedDate":10-20-16
}]
如下:
[{
"BalanceType":"Cash",
"Balance":350.03,
"CreatedDate":10-20-16
},
{
"BalanceType":"Credit",
"Balance":250.01,
"CreatedDate":10-20-15
},
{
"BalanceType":"LoanAmount",
"Balance":450.21,
"CreatedDate":10-20-14
},
{
"BalanceType":"Securiites",
"Balance":350.03,
"CreatedDate":10-20-16
}]
我已经尝试使用 Max 函数来执行此操作,但我发现它只给出最大指示值,而不是对象。 我错过了什么?
这个问题是相关的,但在 mysql 中,所以它对我不可用。
如果您以C#
格式发布数据以便可以直接使用,这将很有帮助。翻译您的数据,以下是对您的答案的查询:
var src1 = new[] {
new {
BalanceType = "Cash",
Balance = 350.03,
CreatedDate = new DateTime(2016, 10, 20)
},
new {
BalanceType = "Cash",
Balance = 250.01,
CreatedDate = new DateTime(2015, 10, 20)
},
new {
BalanceType = "Cash",
Balance = 450.21,
CreatedDate = new DateTime(2014, 10, 20)
},
new {
BalanceType = "Securiites",
Balance = 350.03,
CreatedDate = new DateTime(2016, 10, 20)
}
};
var src2 = new[] {
new {
BalanceType = "Cash",
Balance = 350.03,
CreatedDate = new DateTime(2016, 10, 20)
},
new {
BalanceType = "Credit",
Balance = 250.01,
CreatedDate = new DateTime(2015, 10, 20)
},
new {
BalanceType = "LoanAmount",
Balance = 450.21,
CreatedDate = new DateTime(2014, 10, 20)
},
new {
BalanceType = "Securiites",
Balance = 350.03,
CreatedDate = new DateTime(2016, 10, 20)
}
};
var ans1 = from r in src1
group r by r.BalanceType into rg
let latest = rg.Max(r => r.CreatedDate)
select new { BalanceType = rg.Key, Balance = rg.Where(r => r.CreatedDate == latest).FirstOrDefault().Balance, CreatedDate = latest };
var ans2 = from r in src2
group r by r.BalanceType into rg
let latest = rg.Max(r => r.CreatedDate)
select new { BalanceType = rg.Key, Balance = rg.Where(r => r.CreatedDate == latest).FirstOrDefault().Balance, CreatedDate = latest };
我假设如果有多个最新的日期BalanceType
,选择哪个并不重要,所以我使用了第一个。如果你的DateTime
确实有时间,你可能会用Single()
替换FirstOrDefault()
,如果你的假设是错误的,你的程序崩溃。