3

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?

Martijn Burger
  • 7,315
  • 8
  • 54
  • 94
  • 2
    Something like this maybe? http://stackoverflow.com/questions/18547354/c-sharp-linq-find-duplicates-in-list – Mike Schwartz Jan 28 '14 at 15:44
  • With LINQ you can easily group by account number, filter out all groups that have just one item (so you are left with only dupes), sort each group by creation date descending (so the first item in each group is the most recent) and take it from there. – Jon Jan 28 '14 at 15:46
  • It might not be obvious from the question, but I tried lots of things. I am not very familiar with linq and I could only find examples for a single variable list, instead of a list of objects. So it's not a duplicate question from http://stackoverflow.com/questions/18547354/c-sharp-linq-find-duplicates-in-list I tried to keep my question clean and on question, instead of littering it with now working code. – Martijn Burger Jan 29 '14 at 10:15

3 Answers3

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
}
Bas
  • 26,772
  • 8
  • 53
  • 86
2
duplicates = entitiesList.GroupBy(e => e.accountNumber)
                         .Where(g => g.Count() > 1)
                         .Select(g => g.OrderByDescending(x => x.createdon));
L.B
  • 114,136
  • 19
  • 178
  • 224
0
    List<ListItem> entitiesList = new List<ListItem>();
    var filtered = entitiesList.GroupBy(x => x.accountNumber).Where(g => g.Count() > 1).ToList().OrderByDescending(x => x.createdon);
BRAHIM Kamel
  • 13,492
  • 1
  • 36
  • 47