从 C# List<object> 中获取重复项

3

我有以下的列表定义:

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
    }
}

实体列表中的账户号码存在重复。我想找到重复的账户号码,对具有非最新创建日期的位置GUID执行操作。如何操作列表以仅获取重复项的账户号码、最近创建的locationGuid和(较旧的)locationGuid?


2
像这样的东西可能吗?https://dev59.com/LmMl5IYBdhLWcg3wP1LE - Mike Schwartz
使用LINQ,您可以轻松按帐户号分组,过滤掉只有一个项目的所有组(因此只剩下重复项),按创建日期降序对每个组进行排序(因此每个组中的第一项是最近的),然后从那里开始。 - Jon
从问题中可能不太明显,但我尝试了很多方法。我对linq不是很熟悉,只能找到单个变量列表的示例,而不是对象列表的示例。因此,这不是来自https://dev59.com/LmMl5IYBdhLWcg3wP1LE的重复问题。我试图保持我的问题干净和简洁,而不是用无效的代码来混淆它。 - Martijn Burger
3个回答

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
}

2
duplicates = entitiesList.GroupBy(e => e.accountNumber)
                         .Where(g => g.Count() > 1)
                         .Select(g => g.OrderByDescending(x => x.createdon));

0
    List<ListItem> entitiesList = new List<ListItem>();
    var filtered = entitiesList.GroupBy(x => x.accountNumber).Where(g => g.Count() > 1).ToList().OrderByDescending(x => x.createdon);

您不应该按照“createdon”属性排序。 - binard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接