1

Is there a better/quicker way to check if from a list of objects at least one object has a certain property?

@{if (Model.StockPositions.Count(x => x.Kaufpreis != 0) > 0) {

This will not stop after the first positive hit, will it?

Cœur
  • 37,241
  • 25
  • 195
  • 267
peter
  • 2,103
  • 7
  • 25
  • 51

1 Answers1

7

Well an alternative would be:

@{if (Model.StockPositions.Any(x => x.Kaufpreis != 0) {

If you're interested in the performance difference between Count() and Any(), you might find this answer helpful.

Community
  • 1
  • 1
Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79
  • @peter To answer your second question about stopping. You are correct in that `Count` must go through every item in the list before it can return a result. `Any` is more efficient, because it can stop and return a value as soon as the first item that meets the condition is found. – Bradley Uffner Mar 15 '18 at 11:01