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的功能?
animals.ToLookup(a => a.FoodTypes)
。 - undefinedGroupBy
+ToDictionary
。 - undefined