Home > Back-end >  How to Use LINQ to query to extract Subqueries
How to Use LINQ to query to extract Subqueries

Time:12-29

I'm trying to write a code inside of the main class below. What I need is: string format.

     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;
            }

        }
    }

Could you please correct my answer in the comment or write a new answer there? Thanks

CodePudding user response:

I don't disagree with Dmitry's answer, but I think combining the checks into a single where probably makes the code read more fluidly

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

As to why your attempt didn't work; not every element in the list is a Child (a Child is a Person but not necessarily the other way round) - they are all capable of behaving like a Person but to be a Child requires a cast before you can access properties that are only available on a Child


You've massively edited your question and not given any indication what the new criteria are. The pattern remains the same:

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

CodePudding user response:

You can try OfType() construction to filter out all Children from Persons:

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}");

Edit: If you don't want to use OfType, you can put Select and Where:

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 
  • Related