0

I need to set a variable's value to the value of a property that is nested in several Lists. Each list only has one item except for one list. I'm trying to do this:

var myValue = myListA[0].myListB[0].myListC[0].
              myListD.Where(x => x.Name == "Misc Expenses").myListE[0].price;

This produces a compile time error that says myListD does not contain a definition for myListE. What is the correct syntax?

1
  • 1
    Where does myListE come from? What type does it belong to, and what are the types of the other values in your code? Commented Apr 25, 2022 at 19:53

1 Answer 1

4

After the .Where clause, you need to to .First() (or .ToList()) in order to apply the Where clause:

var myValue = myListA[0].myListB[0].myListC[0].
              myListD.Where(x => x.Name == "Misc Expenses").First().myListE[0].price;

Technically, though, you can replace that .Where with .First directly, too:

var myValue = myListA[0].myListB[0].myListC[0].
              myListD.First(x => x.Name == "Misc Expenses").myListE[0].price;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that's what I was missing. I didn't know you could use First() like you have in the second piece of code. That's interesting.
Or, preferably, Single()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.