当前位置 : 主页 > 编程语言 > c语言 >

c# – Linq从nestes列表中选择peroperty

来源:互联网 收集:自由互联 发布时间:2021-06-25
那是我的代码: class Controller { public ListAction Actions {get; set;}}class Action { public int Id {get; set; public bool IsSelected {get; set;}}ListController controllers = GetControllers();var toAdd = viewModel.PermissionControll
那是我的代码:

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(x => x.Actions.Where(z => z.IsSelected)) // i Am having problem there

你有一个问题,在哪里需要一个bool来确定是否应该包括这个但你提供另一个产生动作而不是一个bool的地方.也许你想要:

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

如果可以重复并且您不想要它们,请在SelectMany之后使用Distinct.

网友评论