Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process List Using LINQ?

In my c# MVC4 application, I have a list of strings. Each odd element in the list is a datetime. The even element before each of them is a unique identifier.

For instance: [0] is A7M0066 [1] is 2007-01-06 06:24:00.000

I want to process the list and add the top 5 most recent pairs based on datetime in the odd elements to another list of strings. Im not sure where to begin but Im assuming it will require LINQ.

Using Keith's answer below and testing I realized that what I actually need has changed. Using his approach, I get 5 results that are most recent but 3 of them have the same id. I need the end result to all have a unique id. Basically I need to keep 1 of the 3 entries that are the same and continue processing until all 5 are unique.

like image 426
HendPro12 Avatar asked Nov 29 '22 13:11

HendPro12


1 Answers

var items =
    list.Where((x, i) => i%2 == 0)
        .Zip(list.Where((x, i) => i%2 == 1), (f, s) => new {Id = f, Date = s})
        .OrderByDescending(x => x.Date)
        .DistinctBy(x => x.Id, null)   // see note later in this answer....
        .Take(5)
        .ToList();

this will zip the even elements with the odd elements and turn them into an Object with Id and Date as fields. Then sorts by the date, and takes the 5 latest

so you can then iterate over each object and do as you wish.

ie, an example use to print out the 5 to the console...

items.ForEach(x => Console.WriteLine("{0} {1}", x.Id, x.Date));

for doing unique IDs with the greatest date..... refer LINQ: Distinct values

and use the extension method shown by Mr Skeet ... except I've improved it a bit, my version is :-

public static class DistinctLinq
    {
        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
            this IEnumerable<TSource> source,
            Func<TSource, TKey> keySelector,
            IEqualityComparer<TKey> comparer)
        {
            var knownKeys = new HashSet<TKey>(comparer);
            return source.Where(element => knownKeys.Add(keySelector(element)));
        }
    }
like image 192
Keith Nicholas Avatar answered Dec 05 '22 03:12

Keith Nicholas