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 trial

C#

Create a variable named anyBlueBirds and write a LINQ query using the Any method to assign a boolean value if there are

What am I doing wrong here?

var birds = 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 }, new Bird { Name = "Canary", Color = "Yellow", Sightings = 0 }, new Bird { Name = "Blue Jay", Color = "Blue", Sightings = 1 }, new Bird { Name = "Crow", Color = "Black", Sightings = 11 }, new Bird { Name = "Pidgeon", Color = "White", Sightings = 10 } };

var anyBlueBirds = new bird if anyBlueBirds.Any( b => b.color == "Blue") { return true; }

3 Answers

This is what I did and it worked:

var anyBlueBirds = false; if (birds.Any(b => b.Color == "Blue")) { anyBlueBirds = true; }

Steven Parker
Steven Parker
231,236 Points

:point_right: You're close, but you have a few issues yet:

  • You won't be creating a new object here, just assign the result of the query directly to the variable.
  • You also won't need an if. The Any method itself returns a boolean result.
  • Be sure to base the query on the birds list (not on your own variable).
Kevin Gates
Kevin Gates
15,053 Points

What Wesley Githens said is true, however you can simplify it even more. Remember, the Any, All, and Contains methods return booleans, so you can assign their results to the variables.

var anyBlueBirds = birds.Any(b => b.Color == "Blue");
Kevin Gates
Kevin Gates
15,053 Points

FYI, full context:

QUESTION: Create a variable named anyBlueBirds and write a LINQ query using the Any method to assign a boolean value if there are any Bird objects in the birds list that have the value "Blue" in the Color property.

Starting Code and Result:

var birds = 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 },
    new Bird { Name =  "Canary", Color = "Yellow", Sightings = 0 },
    new Bird { Name =  "Blue Jay", Color = "Blue", Sightings = 1 },
    new Bird { Name =  "Crow", Color = "Black", Sightings = 11 },
    new Bird { Name =  "Pidgeon", Color = "White", Sightings = 10 }
};

var anyBlueBirds = birds.Any(b=>b.Color == "Blue");