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?
This means $first returns the first order type for the documents between the beginning of the partition and the current document.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With