什么是立即执行LINQ查询最便宜的方式最便宜、方式、LINQ

2023-09-03 06:21:44 作者:玩笑而已

这个问题进入了我的脑海里,而产生的样本数据的SO-答案。 我不喜欢通过 Tbl.Rows.Add 添加数据行逐一的详细办法,所以我已经创建了一个什么也不做,但隐含添加行这个伪LINQ查询

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

正如你可以看到我不需要查询的结果的话,那是唯一的目的就是迭代,并调用 DataTable.Rows.Add 。所以结果是已经在数据表本身可和从查询无需

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.

诚然,这个问题有点hyphotetical因为不会使用FE有很大的不同了ToList ,通常查询的目的是返回的东西。

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.

但无论如何,什么是最便宜的方式(在内存占用,运行时间方面)来执行LINQ查询时,只有执行,而不是结果的问题?

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?

修改:好吧,thisquestion是一个快速射击和一个鸡和蛋的问题。我想,以减少20行code为一条直线,但注意到,我需要某种形式的数据源中的LINQ查询。为此我创建的阵列。但是,在这一点上我可以简单地使用for-each循环以及添加的数据行。

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.

结论:使用LINQ查询的就是它的功能:一个的查询的。那么这个问题是没有意义的,因为没有的最便宜的方式,但只返回正确的结果。

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.

推荐答案

我只是把它改写为的foreach

For Each y As String in years
    tbl.Rows.Add(y)
Next

它更清楚你的意图是这样,它执行的时候了。

It's much more clear what your intention is this way, and it executes right away.