You can read all the C# performance tips from the following links,
Many times, developers use List.Count() to check whether a list has data or is empty, before iterating. Here, we will compare the execution time of List.Count() and List.Any().
List.Count()
- Stopwatch watch = new Stopwatch();
- List < string > strs = new List < string > () {
- "Akshay",
- "Patel",
- "Panth",
- "Patel"
- };
- watch.Start();
- if (strs.Count() > 0) {}
- Console.WriteLine("List.Count()-{0}", watch.Elapsed);
List.Any()
- watch.Restart();
- if (strs.Any()) {}
- Console.WriteLine("List.Any() - {0}", watch.Elapsed);
Result
The result suggests that we should use List.Any() over List.Count() wherever possible.