I have made a small application to practice lambda expressions. I am new to using this technique and I want to become familiar with using them in my day to day coding as I realise how powerful they can be.
I have made a Class named Pet each pet has a Name and an Age I have added 4 pets to my Pet class.
I want to get the pets name who has an age of 1 using a Where and Select clause. However when I run my code instead of returning the pets name I get System.Collections.Generic.List 1 [System.String]
My code is as follows
Pet class
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
Program Class
var pets = new Pet[]
{
new Pet {Name="Sharo", Age=8 },
new Pet {Name="Rex", Age=4 },
new Pet {Name="Strela", Age=1 },
new Pet {Name="Bora",Age=1 }
};
p = pets.Where(pet => pet.Age == 1).Select(pet => pet.Name).ToList();
Console.WriteLine(p);
FirstorSingle(throws exception if more than one).string petname = pets.First(p => p.Age == 1).Name;. Note that this throws aNullRefernceExceptionif there are none, you can useConsole.WriteLine(pets.FirstOrDefault(p => p.Age == 1)?.Name);