4

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?

3
  • 2
    Something like this maybe? stackoverflow.com/questions/18547354/… Commented Jan 28, 2014 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. Commented Jan 28, 2014 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 stackoverflow.com/questions/18547354/… I tried to keep my question clean and on question, instead of littering it with now working code. Commented Jan 29, 2014 at 10:15

3 Answers 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
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

1 Comment

You don't order by the 'createdon' attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.