如何使用 LINQ 查询来提取子查询

How to Use LINQ to query to extract Subqueries

我正在尝试在下面的 class 主体中编写代码。我需要的是: 字符串格式。

     class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine("Hello World");
            List<Person> human = new List<Person>()
            {
              new Person("Sarah", 18), new Person("Peter", 33),
              new Person("Paul", 29), new Child("Kevin", 15, true), new Child("Maria", 9, false)
            };
 
          
        }
//
        class Person
        {
            public string Firstname { get; set; }
            public int Age { get; set; }

            public Person(string fn, int ag)
            {
                this.Firstname = fn;
                this.Age = ag;
            }

        }
//
        class Child : Person   
        {
            public bool IsMale { get; set; }

            public Child(string fn, int ag, bool isM) : base(fn, ag) 
            {
                this.IsMale = isM;
            }

        }
////new feature:
public virtual string CalMe()
{
return "Hiii";
}
    }

能否请您在评论中更正我的答案或在那里写一个新答案? 谢谢

您可以尝试 OfType() 构造以从 Persons:

中过滤掉所有 Children
var femaleChildren = human
  .OfType<Child>()                // children only
  .Where(child => !child.IsMale); // which are not male

foreach (var child in femaleChildren)
  Console.WriteLine($"{child.Firstname} {child.Age}");

编辑:如果你不想用OfType,你可以把SelectWhere:

var femaleChildren = human
  .Select(item => item as Child)  // either Child or null
  .Where(item => item != null)    // children only, no nulls 
  .Where(child => !child.IsMale); // which are not male 

我不反对 Dmitry 的回答,但我认为将检查组合成一个可能会使代码阅读起来更流畅

human.Where(h => h is Child c && !c.IsMale)

至于为什么你的尝试没有成功;并非列表中的每个元素都是 Child(Child 是一个人,但不一定是相反的方式)——它们都能够表现得像一个人,但又是一个 Child需要转换才能访问仅在 Child

上可用的属性

您对问题进行了大量编辑,但没有给出任何新标准的指示。模式保持不变:

cars.Where(c => c is SubCar sc && sc.SomeSubCarOnlyProperty == someValue