As I was looking the difference between Count and Count(), I thought to glance at the source code of Count()
. I saw the following code snippet in which I wonder why the checked
keyword is necessary/needed:
int num = 0; using (IEnumerator<TSource> enumerator = source.GetEnumerator()) { while (enumerator.MoveNext()) { num = checked(num + 1); } return num; }
The source code:
// System.Linq.Enumerable using System.Collections; using System.Collections.Generic; public static int Count<TSource>(this IEnumerable<TSource> source) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } ICollection<TSource> collection = source as ICollection<TSource>; if (collection != null) { return collection.Count; } IIListProvider<TSource> iIListProvider = source as IIListProvider<TSource>; if (iIListProvider != null) { return iIListProvider.GetCount(onlyIfCheap: false); } ICollection collection2 = source as ICollection; if (collection2 != null) { return collection2.Count; } int num = 0; using (IEnumerator<TSource> enumerator = source.GetEnumerator()) { while (enumerator.MoveNext()) { num = checked(num + 1); } return num; } }
In its simplest form (without any parameters), the Count() method returns an int indicating the number of elements in the source sequence. IEnumerable<string> strings = new List<string> { "first", "then", "and then", "finally" }; // Will return 4 int result = strings. Count();
The simple answer is no – there is no difference at all. The COUNT(*) function counts the total rows in the table, including the NULL values.
Because it doesn't want to return a negative number in the (admittedly unlikely) event that there are more than 2-billion-odd items in the sequence - or a non-negative but just wrong number in the (even more unlikely) case that there are more than 4-billion-odd items in the sequence. checked
will detect the overflow condition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With