我不知道为什么我会返回IEnumerable而不是List(c#)

时间:2015-03-25 21:35:55

标签: c# list generics ienumerable

List<string> MealNames =  FoodPlanerList.Select( p => p.Meals.ToList().Select(t => t.name).ToList<String>());  

错误CS0266:无法隐式转换类型System.Collections.Generic.IEnumerable<System.Collections.Generic.List<string>>' to System.Collections.Generic.List&#39;。存在显式转换(您是否缺少演员?)(CS0266)(FoodPlanViewer)

我尝试返回一个字符串列表。我有名单。膳食包含字符串名称。我无法返回包含List所有名称的List。

你能给我一些提示吗?

2 个答案:

答案 0 :(得分:2)

你有错字,你的位置错误:

List<string> MealNames =  FoodPlanerList.Select( p => p.Meals).Select(t => t.name).ToList<String>(); 

如果Meals是一个列表,SelectMany将是正确的功能

List<string> MealNames =  FoodPlanerList.SelectMany( p => p.Meals).Select(t => t.name).ToList<String>(); 

也许你也想插入一个不同的操作

List<string> MealNames =  FoodPlanerList.SelectMany( p => p.Meals).Select(t => t.name).Distinct().ToList<String>(); 

答案 1 :(得分:0)

您正在创建列表列表。你会说每个条目都将这个元素添加到输出

p => p.Meals.ToList().Select(t => t.name).ToList<String>()

这是一个清单。所以它的确正如你所说。如果你想要一个事物列表,那么p=> thing必须返回输出的一个元素

你想做什么以及FoodPlannerList是什么样的(它是什么类型)

相关问题