Linq从嵌套列表中选择性能

时间:2018-06-28 12:07:49

标签: c# linq

那是我的代码:

class Controller {
    public List<Action> Actions {get; set;}
}

class Action {
    public int Id {get; set;
    public bool IsSelected {get; set;}
}

List<Controller> controllers = GetControllers();

var toAdd = viewModel.PermissionControllers
    .Where(x => x.Actions != null)
    .Where(x => x.Actions.Where(z => z.IsSelected)) // i Am having problem there
    .ToList();

我想在IEnumerable<int>上设置IsSelected来获得true的动作。没有linq,它将是:

var ints = new List<int>();

foreach (var controller in controllers)
{
    if (controller.Actions != null)
    {
        foreach (var action in Actions)
        {
            if (action.IsSelected)
                ints.Add(action.Id);
        }
    }
}

很不幸,我被困在where上。你能帮我吗?

1 个答案:

答案 0 :(得分:6)

.Where(x => x.Actions.Where(z => z.IsSelected)) // i Am having problem there

您遇到的问题是,Where需要一个bool才能确定是否应包含此内容,但是您提供了另一个Where却产生了动作而不是一个bool。也许你想要

List<int> actionIdList = viewModel.PermissionControllers
    .Where(x => x.Actions != null)
    .SelectMany(x => x.Actions.Where(a => a.IsSelected).Select(a => a.Id)) 
    .ToList();

如果有可能重复并且您不希望重复,请在Distinct之后使用SelectMany