Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrieve the most common element based on the value of a column with C# generics

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()
like image 303
Jan Avatar asked Nov 28 '25 06:11

Jan


1 Answers

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.

like image 102
Kobi Avatar answered Nov 29 '25 20:11

Kobi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!