-2

For list of objects of class Animal

public class Animal
{
    public int id { get; set; }
    public string name{ get; set; }
    public string category { get; set; }
    public int avg_lifespan { get; set; }
}

How can I return the animals with the highest avg_lifespan by category?

e.g. I have a dataset with 50 animals within 5 categories, I want to return, for each category, the animal with the highest average lifespan.

So far, I have this LINQ statement that returns the distinct categories:

var categories = animals.SelectMany(e => e.category).Distinct();

My idea was to iterate through the list of Animal objects, and for each animal in the list, increment some value with the corresponding animal's average lifespan. How can I do this more elegantly ?

crystyxn
  • 1,411
  • 4
  • 27
  • 59

1 Answers1

0

U can also use groupby, select and aggregate function in linq as follows

   static void Main()
    {
        IEnumerable<Animal> animals =
            new List<Animal>()
            {
                new Animal{ category="A",avg_lifespan=1},
                new Animal{ category="A",avg_lifespan=2},
                new Animal{ category="B",avg_lifespan=3},
                new Animal{ category="B",avg_lifespan=5},
                new Animal{ category="B",avg_lifespan=7}

            }
            .GroupBy(x => x.category)
            .Select(x => x.Aggregate((f, s) => f.avg_lifespan >= s.avg_lifespan ? f : s));

        foreach (var animal in animals)
        {
            Console.WriteLine($"category: {animal.category} \t avg_lifespan: {animal.avg_lifespan}");
        }
    }
neelesh bodgal
  • 632
  • 5
  • 14