I have the code below that retrieves the most common maturity from PetsAgeDataTable. I have this code working but I will need to do the same trick on an other column. I therefore need to make it generic and pass a lambda expression so it can be reused. I'm just spending far too much time trying to figure it out there asking if anyone would be kind enough to let me know how... Cheers / Jan Jensen
var Petmaturity = from p in PetsAgeDataTable
where p.Maturity != null //
group p by new { p.Maturity, p.PetId } into gp
select new { Maturity = gp.Key.Maturity, Count = gp.Coeunt() };
var element= Petmaturity.OrderByDescending(s => s.Count).First()
Assuming your method takes a lambda:
Func<Pet, T> getData
Try something like:
public Tuple<T, int> GetMostCommonProperty<T>(IEnumerable<Pet> pets,
Func<Pet, T> getData)
{
var petGroups = from p in pets
let data = getData(p)
where data != null
group p by new { Data = data, p.PetId } into gp
select new { Data = gp.Key.Data, Count = gp.Count() };
var element = petGroups.OrderByDescending(s => s.Count).First();
return Tuple.Create(element.Data, element.Count);
}
Sample use:
Tuple<string, int> mostCommonName = GetMostCommonProperty(PetsAgeDataTable,
pet => pet.Name);
Note that you need a generic return type here (unless it's always int). You can't really return the anonymous type, but you need to return something. Here I chose a Tuple, but you have many options, depending on how you intend to use it.
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