Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get duplicates from C# List<object>

Tags:

c#

list

linq

I have the following List definition:

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

There are duplicates in the accountNumbers of the entitiesList. I want to find the duplicate accountNumbers, do an action on the locationGuids with a createdon date that is not the most recent createdon date of the duplicates. How can I manipulate the list to get only for the duplicates the accountNumber, most recently created locationGuid and the (older) locationGuids?

like image 620
Martijn Burger Avatar asked Sep 11 '25 22:09

Martijn Burger


2 Answers

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
}
like image 146
Bas Avatar answered Sep 13 '25 12:09

Bas


duplicates = entitiesList.GroupBy(e => e.accountNumber)
                         .Where(g => g.Count() > 1)
                         .Select(g => g.OrderByDescending(x => x.createdon));
like image 36
L.B Avatar answered Sep 13 '25 12:09

L.B