Wondering if there is a way to check how to return if a List<>
has any values in it. Usually I will try something like if(List.Count>0)
but is there another way, that returns Boolean preferably?
Asked
Active
Viewed 72 times
0

RealWorldCoder
- 1,031
- 1
- 10
- 16
-
3What's wrong with `(List.Count > 0)`? I hope this isn't about thinking a bool comparison is faster... – Almo Jan 20 '15 at 20:05
-
5On performance between .Count and .Any(): http://stackoverflow.com/a/305156/1141432 – itsme86 Jan 20 '15 at 20:07
-
Summarizing: for clarity, `Any()`. For speed, `.Count`. – Andrew Jan 20 '15 at 20:08
-
@Andrew not quite, `.Any` for speed when you have `IEnumerable` since `.Count` must enumerate and count. – crashmstr Jan 20 '15 at 20:10
-
1Clarity? Only in the eyes of some beholders.. – TaW Jan 20 '15 at 20:11
-
@crashmstr When you say IEnumerable, you mean List as well right? – RealWorldCoder Jan 20 '15 at 20:12
-
@RealWorldCoder a `List
` can get `Count` in O(1), in other words it *knows* the count of objects. If you then do a `Where` getting an `IEnumerable – crashmstr Jan 20 '15 at 20:15`, `Count` will have to enumerate and count the items in the collection, so O(n). -
2There is a difference between `.Count` and `.Count()`.. `IEnumerable
` does not have a `.Count` property. But if people want to know the details, just read Marc Gravell's answer. It is way better than any comment here. – MAV Jan 20 '15 at 20:16 -
@TaW, of course it's a very slight difference in clarity. I liked T.J.Kjaer's comment to that Marc Gravell's answer: *"It signals the precise intent of the developer. If you are not interested in knowing the number of items, but only if there are some, then somecollection.Any() is simpler and clearer than somecollection.Count > 0"*. – Andrew Jan 20 '15 at 20:31
-
@crashmstr, I based my comment on Marc Gravell's answer, which states that *"if you are starting with something that has a .Length or .Count (such as ICollection
, IList – Andrew Jan 20 '15 at 20:33, List , etc) - then this will be the fastest option"*. And in this case, it's a `List<>`.