我有以下列表定义:
class ListItem
{
public int accountNumber { get; set; }
public Guid locationGuid { get; set; }
public DateTime createdon { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<ListItem> entitiesList = new List<ListItem>();
// Some code to fill the entitiesList
}
}
entitiesList的accountNumbers中有重复项。我想找到重复的accountNumbers,在locationGuids上执行一个操作,其创建日期不是重复项的最新创建日期。如何操作列表以仅获取重复项accountNumber,最近创建的locationGuid和(较旧的)locationGuids?
答案 0 :(得分:3)
List<ListItem> entitiesList = new List<ListItem>();
//some code to fill the list
var duplicates = entitiesList.OrderByDescending(e => e.createdon)
.GroupBy(e => e.accountNumber)
.Where(e => e.Count() > 1)
.Select(g => new
{
MostRecent = g.FirstOrDefault(),
Others = g.Skip(1).ToList()
});
foreach (var item in duplicates)
{
ListItem mostRecent = item.MostRecent;
List<ListItem> others = item.Others;
//do stuff with others
}
答案 1 :(得分:2)
duplicates = entitiesList.GroupBy(e => e.accountNumber)
.Where(g => g.Count() > 1)
.Select(g => g.OrderByDescending(x => x.createdon));
答案 2 :(得分:0)
List<ListItem> entitiesList = new List<ListItem>();
var filtered = entitiesList.GroupBy(x => x.accountNumber).Where(g => g.Count() > 1).ToList().OrderByDescending(x => x.createdon);