What's more efficient in .Any and .Count in C# (Extension methods)
-
public void MethodName(ObservableCollection<DataCollection> dataCollection)
{
if (dataCollection != null)
{
IsChecked = dataCollection.Any(o => o.DataCollectionID.Equals(30));IsChecked = dataCollection.Where(o => o.DataCollectionID.Equals(30)).Count() > 0; } }
Can anyone explain me, what could be the most efficient way to use from above two filtering? .Any? or .Where.Count?
Note: Consider that dataCollection has over 10,000 items.
Please advice me. Thank you
-
public void MethodName(ObservableCollection<DataCollection> dataCollection)
{
if (dataCollection != null)
{
IsChecked = dataCollection.Any(o => o.DataCollectionID.Equals(30));IsChecked = dataCollection.Where(o => o.DataCollectionID.Equals(30)).Count() > 0; } }
Can anyone explain me, what could be the most efficient way to use from above two filtering? .Any? or .Where.Count?
Note: Consider that dataCollection has over 10,000 items.
Please advice me. Thank you
The Any clause should be faster because it can run without an iterator (think yield return here), so it stops when it hits the first true condition, i.e. your collection id equaling 30. The Where clause provides an iterator that is driven by the count, so this must complete the iteration - the actual condition of checking for a count greater than 0 happens after the Where clause finishes evaluating.
-
public void MethodName(ObservableCollection<DataCollection> dataCollection)
{
if (dataCollection != null)
{
IsChecked = dataCollection.Any(o => o.DataCollectionID.Equals(30));IsChecked = dataCollection.Where(o => o.DataCollectionID.Equals(30)).Count() > 0; } }
Can anyone explain me, what could be the most efficient way to use from above two filtering? .Any? or .Where.Count?
Note: Consider that dataCollection has over 10,000 items.
Please advice me. Thank you
And to add to what Pete says, if you need to know whichis the most efficient, it's simple enough to time it. Use the Stopwatch class[^] and run a good number of times to eliminate external variance.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
-
public void MethodName(ObservableCollection<DataCollection> dataCollection)
{
if (dataCollection != null)
{
IsChecked = dataCollection.Any(o => o.DataCollectionID.Equals(30));IsChecked = dataCollection.Where(o => o.DataCollectionID.Equals(30)).Count() > 0; } }
Can anyone explain me, what could be the most efficient way to use from above two filtering? .Any? or .Where.Count?
Note: Consider that dataCollection has over 10,000 items.
Please advice me. Thank you
Hi, They are both right. Just to be more accurate Where() does not necessarily enumerate over all elements, that depends on what you put in the condition. In general the advice is to stick to Any().