Search code examples
c#listdictionaryduplicateskeyvaluepair

How to select duplicate value from a list in C# based on condition?


I have a list with date and Fileno as values. I need to find the duplicate date and based on that find the highest Fileno.Then add that keyvalue pair and the distinct pair to the final list. The result should be as shown below.I am able to get the duplicate date but how to compare the duplicate dates and find the highest fileno?

Key  Date       Fileno
 1  10/8/1980   1234
 2  10/8/1980   1345
 3  8/6/1970    4567

Result

 2  10/8/1980   1345
 3  8/6/1970    4567

Code

var list = new List<valuepair>();
list.Add(new valuepair {no=key,comdate=date,filnum=fileno})
Var dup= list.GroupBy(x => comdate.Value).Where(x => comdate.Count() > 1)

Solution

  • Try this:

    var result = data
        .GroupBy(
            i => i.Date,
            (key, group) => group.Single(x => x.Fileno == group.Max(y => y.Fileno)))
        .ToList();