本文介绍了在C#Linq中同时选择“父子集合"到某些模型的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

班长拥有子班收款人,代表他/她下面的员工列表.

The Class Boss has the sub Class Collection Person for representing List of Employees under him/her.

public class Person
{
    public string Name { get; set; }
    public string Department { get; set; }
    public string Gender { get; set; }
}

public class Boss
{
    public string Name { get; set; }
    public string Department { get; set; }
    public string Gender { get; set; }
    public List<Person> Employees { get; set; }
}

Boss John = new Boss()
{
    Name = "Harry",
    Department = "Development",
    Gender = "Male",
    Employees = new List<Person>()
        {
            new Person() {Name = "Peter", Department = "Development",Gender = "Male"},
            new Person() {Name = "Emma Watson", Department = "Development",Gender = "Female"},

        }
}

我的必需收藏应该是

List<Person> Members = new List<Person>()
    {
        new Person() {Name = "Harry", Department = "Development",Gender = "Male"},
        new Person() {Name = "Peter", Department = "Development",Gender = "Male"},
        new Person() {Name = "Emma Watson", Department = "Development",Gender = "Female"},
    }

如何使用LINQ语句从对象John 获得列表成员.请帮助我.

How to achieve the List Members from the object John using LINQ Statement. Kindly assist me.

也请使用LINQ语句为 List<Boss> 中的 Distinct List<Person> Members 提供解决方案.

Kindly provide the Solution also for Distinct List<Person> Members from List<Boss> using LINQ Statement.

推荐答案

您可以像这样简单地做到:

You can simply do it like this:

var list = John.Employees.ToList();

list.Insert(0,
    new Person
    {
        Name = John.Name,
        Department =  John.Department,
        Gender = John.Gender
    });

如果您有List<Boss>,则可以执行以下操作:

If you have a List<Boss>, then you can do something like this:

var result = list
    .SelectMany(x =>
        new [] { new Person { Name = x.Name, Department = x.Department, Gender = x.Gender, EmpID = x.EmpID }}
        .Concat(x.Employees))
    .GroupBy(x => x.EmpID) //Group by employee ID
    .Select(g => g.First()) //And select a single instance for each unique employee
    .ToList();

这篇关于在C#Linq中同时选择“父子集合"到某些模型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 15:06