Search code examples
c#linq

LINQ query that given some As each one with some Bs returns all (ab) pairs


I have some containers that have some properties and contains some items.

public class AnimalDomain
{
    public string Domain {get; set;}
    
    List<Animal> Animals {get; set;}
}

public class Animal
{ 
     public string Name {get; set;}

}

What I want to achieve is that given a list of animal's domains each one containing its own animals, each animal is converted into a tuple that has also the properties of its own domain.

In example

public class ExtendedAnimal
{
     public string DomainName {get; set;}

     public string AnimalName {get; set;}
}

The prototype for the function is

 public IEnumerable<ExtendedAnimal> MergeDomainAndAnimal(IEnumerable<AnimalDomain> input)
 { 
       // some LINQ query.
 }

Solution

  • IEnumerable<ExtendedAnimal> MergeDomainAndAnimal(IEnumerable<AnimalDomain> input) =>
        from domain in input
        from animal in domain.Animals
        select new ExtendedAnimal
        {
            DomainName = domain.Name,
            AnimalName = animal.Name
        };