Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJon Andreas Grenness
5,055 PointsStruggeling to understand LINQ query to find birds
I can't wrap my head around how LINQ queries are meant to be formulated if I have to compare the results in to different lists even when re-watching video multiple times. Some help would be greatly appreciated.
Thank you in advance!
var myBirds = new List<Bird>
{
new Bird { Name = "Cardinal", Color = "Red", Sightings = 3 },
new Bird { Name = "Dove", Color = "White", Sightings = 2 },
new Bird { Name = "Robin", Color = "Red", Sightings = 5 }
};
var yourBirds = new List<Bird>
{
new Bird { Name = "Dove", Color = "White", Sightings = 2 },
new Bird { Name = "Robin", Color = "Red", Sightings = 5 },
new Bird { Name = "Canary", Color = "Yellow", Sightings = 0 }
};
var ourBirds = myBirds.Join(yourBird, b => b.Name, n => b.Name, (myBird, myBird.Name) => myBirds);
2 Answers
Steven Parker
231,268 PointsYou're pretty close, you just need a little "fine tuning":
- the first Join argument should be the name of the 2nd iterable "yourBirds" (plural, instead of "yourBird")
- the inner key selector (third argument) should be
n => n.Name
(with "n" instead of "b") - the 2nd parameter of the result selector isn't used, but its name should not have a membership operator (".")
That 2nd lambda parameter can be anything, but I often like to use "_" (underscore) as the name of a parameter that won't be used. The name "unused" is also good.
Jon Andreas Grenness
5,055 PointsI changed the errors you pointed out, and renamed the (myBird, myBird.Name) => myBird to
var ourBirds = myBirds.Join(yourBirds, b => b.Name, n => n.Name, (bird, name) => bird);
and that worked.
Thanks!