This question came into my mind while generating sample data for a SO-answer.
I don’t like the verbose way of adding DataRows one by one via Tbl.Rows.Add, so i’ve created this pseudo LINQ query that does nothing but adding rows implicitely:
Private Function GetData() As DataTable
Dim years = {"2010/2009", "2009/2008", "2008/2007", "2007/2006", "2006/2005", "2005/2004", "2004/2003"}
Dim tbl = New DataTable
tbl.Columns.Add(New DataColumn("Year"))
' adds DataRows to the DataTable, need Count to execute the query '
Dim c = (From y In years Select tbl.Rows.Add(y)).Count
Return tbl
End Function
As you can see i don’t need the result of the query at all, it’s only purpose is to iterate and call DataTable.Rows.Add. So the result is already available in the DataTable itself and not needed from the query.
Admittedly this question is somewhat hyphotetical because there would not be a big difference in using f.e. ToList and normally a query’s purpose is to return something.
But anyway, what’s the cheapest way(in terms of memory consumption, execution time) to execute a LINQ query when only the execution and not the result matters?
Edit: Ok, thisquestion was a quick-shot and a chicken-and-egg problem. I wanted to reduce 20 lines of code to a single line but noticed that i need some kind of DataSource for the LINQ-Query. Therefor i’ve created the Array. But at this point i could have simply used a for-each loop as well to add the DataRows.
Conclusion: Use a LINQ-Query for what it’s for: a query. Then this question is pointless since there is no cheapest way but only that which returns the correct result.
I’d just rewrite it as a
foreach:It’s much more clear what your intention is this way, and it executes right away.