C# Querying With LINQ Query Operators Aggregates

Calvin Secrest
Calvin Secrest
22,167 Points

Code could not be compiled... Ned help please!

Create a variable named sumOfSightings and assign it to the sum of all the Sightings in the ourBirds list. Bummer! Your code could not be compiled. Please click on "Preview" to view the compiler errors. Restart Preview Get Help Recheck work CodeChallenge.cs

A local variable `sumOfSightings' cannot be used before it is declared Compilation failed.

CodeChallenge.cs
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(yourBirds,
                            mb => mb.Name,
                            yb => yb.Name,
                            (mb, yb) => (mb));

var sumOfSightings = sumOfSightings.Sum(ourBirds, b => Sightings);

2 Answers

Jennifer Nordell
STAFF
Jennifer Nordell
Treehouse Staff

Hi there! You're doing fairly well here, I think. But sumOfSightings is a completely new variable so you can't run the .Sum method on it because it's not initialized yet. However, the Sum method is intended to be run on the ourBirds variable which contains the sightings of both myBirds and yourBirds put together. Take a look:

var sumOfSightings = ourBirds.Sum(b => b.Sightings);

This will retrieve the sum of all sightings in ourBirds and assign it back into the variable sumOfSightings. Hope this helps! :sparkles:

{ 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(yourBirds, mb => mb.Name, yb => yb.Name, (mb, yb) => (mb));

var sumOfSightings = ourBirds.Sum(b => b.Sightings);