consider the following code example:
IEnumerable<Y> myEnumeration = *some linq stuff into a datatable*
If (myEnumeration.Count() > X)
{
foreach(Y bla in myEnumeration)
{
// do something
}
}
Will this result in enumerating 2 times? The count-Call + the foreach? If so, is there any way to avoid one of the enumerations?
Thanks in advance
Edited myEnumeration.Count -> myEnumeration.Count() (extension method)
I put this code to LinqPad to let me show the generated SQL:
IEnumerable<MyTable> myEnumeration = MyTable;
if (myEnumeration.Count() > 1)
{
foreach(MyTable bla in myEnumeration)
{
// do something
}
}
The generated SQL is the following:
SELECT * FROM [MyTable] AS [t0]
GO
SELECT *
FROM [MyTable] AS [t0]
So yes, the data will be retrieved two times from Database. Consider
List<Y> myEnumeration = *some linq stuff into a datatable* **.ToList();**
Yes, that will give you two database calls. Count()
will execute query like:
SELECT COUNT(1) FROM Table WHERE Blah
And then GetEnumerator()
will execute query which gets all required fields:
SELECT Id, Foo, Bar FROM Table WHERE Blah
Actually there is no one correct answer. You should consider on:
Depending on that you should make your decision.
Here is extension:
public static IEnumerable<T> TakeIfMoreThan<T>(
this IEnumerable<T> source, int count)
{
List<T> buffer = new List<T>(count);
using (var iterator = source.GetEnumerator())
{
while (buffer.Count < count && iterator.MoveNext())
buffer.Add(iterator.Current);
if (buffer.Count < count)
{
yield break;
}
else
{
foreach (var item in buffer)
yield return item;
buffer.Clear();
while (iterator.MoveNext())
yield return iterator.Current;
}
}
}
Usage is simple:
foreach(Y bla in myEnumeration.TakeIfMoreThan(X))
{
// do something
}
Thus you will not need to dump all query results in in-memory list. You will use single database call (but it will query for all item fields). And you will not enumerate items if there is less than required number of results.
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