Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List to Dictionary (a map of key and the filtered list as value)

Tags:

c#

lambda

c#-4.0

class Animal
    {
        public FoodTypes Food { get;set;} 
        public string Name { get; set; }
    }
    enum FoodTypes
    {
        Herbivorous,
        Carnivorous
    }

    class Util
    {
        public static Dictionary<FoodTypes,List<Animal>> GetAnimalListBasedOnFoodType(List<Animal> animals)
        {
            Dictionary<FoodTypes, List<Animal>> map = new Dictionary<FoodTypes, List<Animal>>();
            var foodTypes = animals.Select(o => o.Food).Distinct();
            foreach(var foodType in foodTypes)
            {
                if (!map.ContainsKey(foodType))
                    map.Add(foodType, null);
                map[foodType] = animals.Where(o => o.Food == foodType).ToList();
            }
            return map;
        }
    }

The above code is to get the idea of what I am trying to achieve. Now, the question is Is it possible to achieve the functionality of GetAnimalListBasedOnFoodType in a single lambda expression?

like image 829
Srikanth P Vasist Avatar asked Sep 14 '25 04:09

Srikanth P Vasist


1 Answers

Here you go :)

public static Dictionary<FoodTypes, List<Animal>> GetAnimalListBasedOnFoodType(List<Animal> animals)
{
    return animals
        .GroupBy(animal => animal.Food)
        .ToDictionary(
            group => group.Key,
            group => group.ToList());
}
like image 94
MFatihMAR Avatar answered Sep 16 '25 18:09

MFatihMAR