Srikanth P Vasist Srikanth P Vasist - 28 days ago 21
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
{
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?

Answer

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());
}
Comments