我有一个如下所示的列表:
//
// main.m
// ex-5.9
//
// Created by george on 05/07/2016.
// Copyright © 2016 george. All rights reserved.
// Program to reverse the digits of a number
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
int number, right_digit;
NSLog(@"Enter your number.");
scanf("%i", &number);
if(number < 0){
number = ABS(number);
do {
right_digit = number % 10;
NSLog(@"%i", right_digit);
number /= 10;
} while (number != 0);
NSLog(@"-");
}else{
do {
right_digit = number % 10;
NSLog(@"%i", right_digit);
number /= 10;
} while (number != 0);
}
}
return 0;
}
我需要一个linq查询,根据具有最新日期的RefId让我与众不同,如下所示:
List<MyObjects> list:
list[0] - Id: 1; RefId:101; Date:22/06/2016
list[1] - Id: 2; RefId:102; Date:24/06/2016
list[2] - Id: 3; RefId:101; Date:26/06/2016
list[3] - Id: 4; RefId:103; Date:28/06/2016
这里重复RefId-101但它的第一个日期值是旧的,因此被删除。 提前谢谢。
答案 0 :(得分:4)
在RefId
之前使用Linq群组,然后按Date
对每个群组进行排序,然后从每个群组中先取出:
list.GroupBy(x => x.RefId).Select(x => x.OrderByDescending(y => y.Date).FirstOrDefault());
或使用查询语法:
List<MyObjects> results = (from x in list
group x by x.RefId into grp
select grp.OrderByDescending(y => y.Date).FirstOrDefault()
).ToList();
答案 1 :(得分:4)
您可以使用GroupBy
按RefId
进行分组,然后按Date
对这些群组进行排序,并选择第一个:
var result = list.GroupBy(o => o.RefId)
.Select(g => g.OrderByDescending(gx => gx.Date).First())
.ToList();
由于您需要最新 Date
,因此您需要OrderByDescending
。
答案 2 :(得分:2)
我认为最好避免调用.FirstOrDefault()
。这是另一种选择:
var newList =
list
.GroupBy(x => x.RefId)
.SelectMany(x => x.OrderByDescending(y => y.Date).Take(1))
.ToList();