Изучаю LINQ, операцию JOIN. Вот код:
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Pet
{
public string Name { get; set; }
public Person Owner { get; set; }
}
class Cat : Pet
{ }
class Dog : Pet
{ }
class Program
{
static void Main(string[] args)
{
Person magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
Person terry = new Person { FirstName = "Terry", LastName = "Adams" };
Person charlotte = new Person { FirstName = "Charlotte", LastName = "Weiss" };
Person arlene = new Person { FirstName = "Arlene", LastName = "Huff" };
Person rui = new Person { FirstName = "Rui", LastName = "Raposo" };
Person phyllis = new Person { FirstName = "Phyllis", LastName = "Harris" };
Cat barley = new Cat { Name = "Barley", Owner = terry };
Cat boots = new Cat { Name = "Boots", Owner = terry };
Cat whiskers = new Cat { Name = "Whiskers", Owner = charlotte };
Cat bluemoon = new Cat { Name = "Blue Moon", Owner = rui };
Cat daisy = new Cat { Name = "Daisy", Owner = magnus };
Dog fourwheeldrive = new Dog { Name = "Four Wheel Drive", Owner = phyllis };
Dog duke = new Dog { Name = "Duke", Owner = magnus };
Dog denim = new Dog { Name = "Denim", Owner = terry };
Dog wiley = new Dog { Name = "Wiley", Owner = charlotte };
Dog snoopy = new Dog { Name = "Snoopy", Owner = rui };
Dog snickers = new Dog { Name = "Snickers", Owner = arlene };
List<Person> people =
new List<Person> { magnus, terry, charlotte, arlene, rui, phyllis };
List<Cat> cats =
new List<Cat> { barley, boots, whiskers, bluemoon, daisy };
List<Dog> dogs =
new List<Dog> { fourwheeldrive, duke, denim, wiley, snoopy, snickers };
var query = from person in people
join dog in dogs on new { person.FirstName, person.LastName } equals new { dog.Owner.FirstName, dog.Owner.LastName }
join cat in cats on new { person.FirstName, person.LastName } equals new { cat.Owner.FirstName, cat.Owner.LastName }
select new {person, dog, cat};
foreach(var item in query)
{
Console.WriteLine($"{item.person.FirstName} {item.person.LastName} owns cat {item.cat.Name} and dog {item.dog.Name}");
}
}
Результат:
Magnus Hedlund owns cat Daisy and dog Duke
Terry Adams owns cat Barley and dog Denim
Terry Adams owns cat Boots and dog Denim
Charlotte Weiss owns cat Whiskers and dog Wiley
Rui Raposo owns cat Blue Moon and dog Snoopy
Как видно, объект с именем Terry Adams дублируется из-за наличия у него двух котов.
Вопрос: Как нужно изменить запрос, чтобы в анонимный клас попадал список(ну или массив) котов и собак, и соответственно избежать дубликата
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости