本文介绍了使用LINQ在C#中构建级联列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要显示部门和子部门的列表.我正在正确加载部门列表.

I have a need to display a list of departments and sub-departments. I am loading the list of departments properly.

这时,我有:

var deparmentList = Departments.LoadList();
var departments = new List<ListItem>(
  from department in departmentList
  select new ListItem {
    Text = department.Name,
    Value = department.Id.ToString(),
    IsSelected = department.IsActive
  }
);

我现在需要加载子部门列表.每个子部门都有一个IdDepartmentIdName.但是,我只想获取与所选部门关联的子部门.目前,我有以下内容:

I now need to load the list of sub-departments. Each sub-department has an Id, DepartmentId, and Name. However, I only want to get the sub-departments associated with departments that are selected. Currently, I have the following:

var subDepartmentList = SubDepartment.LoadList(); 
var subdepartments = new List<ListItem>(
  from subdepartment in subDepartmentList
//  where ?
  select new ListItem {
    Text = subdepartment.Name,
    Value = subdepartment.Id.ToString(),
    IsSelected = false
  }
);

我不确定如何在两者之间进行联接或过滤.如何在LINQ中做到这一点?

I'm not sure how to do the join or filter between the two. How do I do this in LINQ?

推荐答案

var selectedDepartmentSubDepartments = 
    from dep in departments 
    join subDep in subDepartmentList
    on dep.Value equals subDep.Id.ToString()
    where dep.IsSelected
    select new ListItem {
        Text = subDep.Name,
        Value = subDep.Id.ToString(),
        IsSelected = false
    };
var subdepartments = new List<ListItem>(selectedDepartmentSubDepartments);

这篇关于使用LINQ在C#中构建级联列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 19:42