Srikanth P Vasist Srikanth P Vasist - 4 months ago 48
C# Question

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

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

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?


Here you go :)

public static Dictionary<FoodTypes, List<Animal>> GetAnimalListBasedOnFoodType(List<Animal> animals)
    return animals
        .GroupBy(animal => animal.Food)
            group => group.Key,
            group => group.ToList());