Linq打开了一个嵌套的foreach

时间:2011-03-21 11:23:20

标签: c# linq

如何将以下嵌套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语法更多,如果可能的话

4 个答案:

答案 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);
        }

..可能有用!