11

Any advice on when DataTable.Select should be used versus LINQ Select when dealing with an in-memory DataTable?

I find LINQ syntax easier and more powerful, but I'm not sure if there are performance or other issues which make a DataTable select preferable.

(I'm using a third party API that provides a DataTable that has been pre-populated from the database. I need to filter that further in-memory.)

4

3 回答 3

10

根据个人经验,我尽量避免使用 Datatable.Select。我发现它很慢并且有一些奇怪的错误。

我遇到的一个(由 Microsoft 确认并记录的)错误是,当语句中有括号时,DataTable.Select 并不总是正确评估 AND 条件。

例如,(Col1 > 1) AND (Col < 10) 可能无法返回正确答案,而 Col1 > 1 AND Col < 10 将正常工作。

此错误不会出现在每台计算机上。在我的情况下,我使用的检查在我的开发平台和除一台之外的每台客户端计算机上运行良好。在我发现这个错误后,我开始转向使用 LINQ 进行选择,并注意到操作速度显着提高。

旁注:无需过多解释,我的公司不使用数据库来存储数据。 我们对 DataTables 的所有操作都涉及从平面文件加载的内存表。所以我说的不是 LINQ 2 SQL,而是 LINQ to Dataset。

于 2009-09-14T15:10:56.340 回答
2

甚至不提及 LINQ,除非绝对必须,否则我不会在任何地方使用 DataTable.Select ,因为在大多数情况下,这意味着在客户端执行一些可能应该在数据库中执行的操作。

更新:我在这里的回答可能有点夸大了。有时有正当理由将 DataTable 用作(希望)小型内存数据库,以最大限度地减少客户端到数据库的往返行程。

于 2009-09-14T14:49:03.793 回答
0

Hmm, are you comparing datasets with LINQ to SQL? If you are, then I'd say just ditch datasets and go with L2S. DataTable.Select assumes you've already populated the datatable with data. This can lead to bad designs where you load more data than you need, just to filter in the client. Get SQL Server to do your querying for you, and work on the resultset it gives you. L2S will read from the database only when you iterate the collection, so it's much easier to formulate your queries before hitting the database.

LINQ to SQL introduces some debugging overhead because it can be awkward to get the dynamically-generated SQL out of it (whereas in datasets you are supplying the SQL in the first place), but in almost all other situations it's far more elegant. The deferred loading functionality is especially useful.

If you're not working with a database, then I'd still prefer LINQ (specifically known as LINQ to Objects in this scenario) over datasets. The syntax is just much easier, and because there are no magic strings (i.e. SQL statements) then it's easier to test and you get compile-time warnings for typos etc.

于 2009-09-14T14:47:17.307 回答