我有以下列表定义:

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

entityList 的 accountNumbers 中存在重复项。我想找到重复的 accountNumbers,对 locationGuids 执行操作,其创建日期不是重复项的最近创建日期。如何操作列表以仅获取 accountNumber、最近创建的 locationGuid 和(旧的)locationGuids 的重复项?

最佳答案

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/

10-13 05:00