Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a lookup?

Hi I have a lookup type that stores strings and ints.

static Lookup<string, int> lookup;
lookup = (Lookup<string, int>)list.ToLookup(i => i.IP, i => i.Number);

But now I need to sort this lookup by the values (number), and get the top 10 keys with their values.

How is this possible?

like image 547
sprocket12 Avatar asked Oct 29 '11 22:10

sprocket12


People also ask

What is $first in Mongodb?

This means $first returns the first order type for the documents between the beginning of the partition and the current document.


2 Answers

Unfortunately elements inside a Lookup cannot be reordered.

But the ToLookup() method has a nice property that elements in all the groupings have the same order as the elements in the original sequence.

This means that with some Linq gymnastics, you can achieve what you want by using GroupBy:

var l = (from l in list
         // group elements by key
         group l by l.IP into g
         // for each group order the elements and take top 10
         select new { g.Key, Items = g.OrderBy(g1 => g1.Number).Take(10)} into g2
         // flaten group into an enumerable using select many
         from g in g2.Items
         select g)
         // get the desired lookup containing the top 10 ordered elements for each key
        .ToLookup(g => g.IP, g => g.Number);
like image 78
Pop Catalin Avatar answered Oct 15 '22 19:10

Pop Catalin


I'm not sure why you are casting a Lookup<string, int> to a Lookup<string, string>, but the general answer you want is:

var list = new List<Test>
    {
            new Test { IP = "A", Number = 1 }, new Test { IP = "A", Number = 3 }, new Test { IP = "A", Number = 4 },
            new Test { IP = "B", Number = 1 }, new Test { IP = "B", Number = 1 }, new Test { IP = "B", Number = 1 },
            new Test { IP = "C", Number = 1 },
            new Test { IP = "D", Number = 1 },
            new Test { IP = "E", Number = 1 }, new Test { IP = "E", Number = 1 }, new Test { IP = "E", Number = 1 }
    };

var values = list.ToLookup(s => s.IP, s => s.Number)
                 .OrderByDescending(s => s.Count())
                 .Take(10);
like image 45
Ritch Melton Avatar answered Oct 15 '22 20:10

Ritch Melton