如何将以下嵌套foreach
循环转换为Linq表达式?
由于
List<Plan> plans = new List<Plan>();
foreach (var planning in plannings)
{
foreach (var plan in planning)
{
plans.Add(plan);
}
}
我希望看到它与lambda表达式(.Select()
)完成比from .. select
语法更多,如果可能的话
答案 0 :(得分:8)
var plans = plannings.SelectMany(p => p);
答案 1 :(得分:3)
List<Plan> plans = plannings.SelectMany(ps => ps).ToList();
答案 2 :(得分:1)
为了完整起见,这是查询语法版本:
var query = from planning in plannings
from plan in planning
select plan;
List<Plan> plans = query.ToList();
答案 3 :(得分:0)
List<Plan> plans = new List<Plan>();
foreach (var plan in plans.SelectMany(planning => planning))
{
newPlans.Add(plan as Plan);
}
..可能有用!