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

标签 c# linq list

我有以下列表定义:

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 和(较旧的)locationGuid?

最佳答案

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
}

关于c# - 从 C# List<object> 中获取重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21410153/

相关文章:

c# - 在 .net core 和 .net Framework 中搜索给出不同输出的注册表项

C# IDE 错误代码

scala - 如何计算两个列表中元素出现次数的乘积?

python - 如何将键值元组列表转换为字典?

c# - MVC 项目中的 jQuery 错误 : Datepicker is not a function

F# 中的 C# lambda (=>) 语法

c# - 具有安全转换和空验证的 Linq

C# 如何用另一个集合中的对象替换一个集合中的对象

c# - 对多个 ControlCollection 进行 Foreach

python - 打印直方图