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
  • 34,719
  • 24
  • 185
  • 251
peter
  • 2,063
  • 6
  • 23
  • 50

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,311
  • 7
  • 45
  • 76
  • 1
    Thanks :o) didn't think of that! – peter May 26 '13 at 02:38
  • @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