Get the most common item based on the value of a column with generic C #

I have the code below that extracts the most common maturity from PetsAgeDataTable. This code works for me, but I will need to do the same trick in another column. So I have to make it general and pass in a lambda expression so that it can be reused. I just spend too much time trying to figure it out there, asking if anyone would be kind enough to let me know how ... Greetings / 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()
+3
source share
1 answer

Assuming your method accepts 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);
}

Using an example:

Tuple<string, int> mostCommonName = GetMostCommonProperty(PetsAgeDataTable,
                                                          pet => pet.Name);

, ( int). , - . Tuple, , , .

+1

All Articles