1

I've got a model that has an ICollection of telephone numbers. In my view I want to display the value for the record that is marked as Primary.

@Html.DisplayFor(model => model.Telephones.Where(a=>a.Primary==true).Number)

The .Number is not allowed in the Linq syntax. How would one go about making the above line work or rather what is the proper way to display the number?

I probably should do the logic in the controller and put the value in a view model but it seems like this should be doable.

3
  • I feel its better to have a readonly property called PrimaryNumber inside which you can do the linq operation to fetch the Number. Then bind the displayfor to that number property. Commented Feb 19, 2014 at 19:11
  • Why do you feel this way? Commented Feb 19, 2014 at 19:46
  • I felt that way because the model logic should reside in Model layer Commented Feb 20, 2014 at 5:10

1 Answer 1

3

The Where extension method returns an IEnumerable<T>. If you just want the first item which satisfies the condition, use First:

@Html.DisplayFor(model => model.Telephones.First(a => a.Primary).Number)

If you also need to ensure that exactly one item in the set satisfies the condition (and throw an exception otherwise), consider using Single:

@Html.DisplayFor(model => model.Telephones.Single(a => a.Primary).Number)
Sign up to request clarification or add additional context in comments.

3 Comments

Should be mindful of case if no number is found. I believe in that case First returns null which will cause NullRef exception. Need to handle that case.
@LB2 You're thinking of FirstOrDefault. First will raise an InvalidOperationException if it can't find at least one element which satisfies the condition.
Also, be aware that if you're using .Single, you will actually issue a Top 2 vs First which does Top 1. The only reason to use Single is if you need the exception to be thrown if more than one exists.

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.