简体   繁体   English

Linq 过滤子 class 并返回父 class?

[英]Linq filter child class and return parents class?

I am trying filter class list inside parents class but need to return parents class.我正在尝试在父母 class 中过滤 class 列表,但需要返回父母 class。

C# Code: C# 代码:

        // Must return `Parents` class
        public Parents FilterByAge()
        {
            Parents Family = new Parents() { FatherName = "John", MotherName = "Mary" };
            Family.Children = new List<Children>(){
                new Children{ Name = "Peter",Age=20},
                new Children{ Name = "Alber",Age=15},
                new Children{ Name = "Alex",Age=10},
                new Children{ Name = "Ched",Age=5},
            };
            // Fail here, It will return `Children` class instead of `Parents` class.
            return Family.Children.Where(o => o.Name == "Peter");

            // Fail too, will show 'Family does not contain a definition for Where'
            //return Family.Where(f => f.Children.Any(c => c.Name == "Peter"));

        }
        class Parents
        {
            public string FatherName { get; set; }
            public string MotherName { get; set; }
            public List<Children> Children { get; set; }
        }
        class Children
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }

How to return parents class after Linq filter the child class?(Just use Linq and return in one line and do not modify data or create a new class)如何在 Linq 过滤子 class 后返回父母 class?

As List<T> has a RemoveAll method which modifies the list in place:由于List<T>有一个RemoveAll方法可以修改列表:

public Parents FilterByAge()
{
    Parents family = new Parents() { FatherName = "John", MotherName = "Mary" };
    family.Children = new List<Children>()
    {
        new Children{ Name = "Peter", Age = 20 },
        new Children{ Name = "Alber", Age = 15 },
        new Children{ Name = "Alex", Age = 10 },
        new Children{ Name = "Ched", Age =5 }
    };

    family.Children.RemoveAll(child => child.Name != "Peter");

    return family;
}

Just use Linq and return in one line. : Create new object and assign parent properties. :新建 object 并分配父属性。 And assign filtered list for Children .并为Children分配过滤列表。

return new Parents() 
{ 
    FatherName = Family.FatherName, 
    MotherName = Family.MotherName,
    Children = Family.Children.Where(o => o.Name == "Peter")
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM