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;
}
}
上面的代码是为了了解我想要实现的目标。现在,问题是 是否可以在单个lambda表达式中实现GetAnimalListBasedOnFoodType的功能?
答案 0 :(得分:5)
你走了:))
public static Dictionary<FoodTypes, List<Animal>> GetAnimalListBasedOnFoodType(List<Animal> animals)
{
return animals
.GroupBy(animal => animal.Food)
.ToDictionary(
group => group.Key,
group => group.ToList());
}
答案 1 :(得分:0)
您希望使用GroupBy方法传入要对动物进行分组的属性。然后,您可以使用ToDictionary方法根据分组创建字典。
例如:
public static Dictionary<FoodTypes, List<Animal>> GetAnimalListBasedOnFoodType(List<Animal> animals)
{
var animalFoodMap = animals.GroupBy(animal => animal.Food)
.ToDictionary(animalGroup => animalGroup.Key, x => animalGroup.ToList());
return animalFoodMap;
}