给定具有未知数量的不同字符串值的值列表,如何获取每个字符串的最新值?
我获得了一个具有以下三个属性的对象列表:Balance,BalanceType和CreatedDate。进入,我知道可以设置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函数执行此操作,但我发现它只给出了最大指示值,而不是对象。我错过了什么?
Spring boot docs是相关的,但是在mysql中,它对我来说无法使用。
答案 0 :(得分:2)
如果您以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
,那么选择哪个并不重要,所以我使用了第一个。如果您的FirstOrDefault()
实际上有时间,则可以将Single()
替换为onCreateViewHolder
,如果您的假设错误,则会导致您的计划崩溃。