哪个更好? DataTable.Select() 或 Linq 用于过滤对象?
我正在存储自定义类类型的对象集合。我给出了下面的类型。
public class AnonymousClient
{
private string ipAddress, city, country, category;
private Guid id;
}
我可能必须根据城市、国家/地区、类别等过滤对象。我可以想到两种方法 -
- 将其存储在字典中
字典
并使用 Linq 来过滤 对象。 - 将其存储在
DataTable
中 成员的多列 并使用 DataTable.Select() 来 过滤记录。
我猜它们都在内部循环。哪一个更快、更优雅?有什么见解吗?
I'm storing a collection of objects of custom class type. I've given the type below.
public class AnonymousClient
{
private string ipAddress, city, country, category;
private Guid id;
}
I may have to get the objects filtered based on city, country, category etc. I'm able to think of two ways -
- Storing it in a dictionary
Dictionary<Guid, AnonymousClient>
and using Linq to filter the
objects. - Storing it in a
DataTable
with
multiple columns for the members
and using DataTable.Select() to
filter the records.
I guess both of them loop internally. Which one is faster and elegant? Any insights?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 DataTable 会增加相当多的开销。设置查询后,运行查询会更容易,因为它的代码已经创建,但运行速度不会那么快。
如果您想使用
id
查找项目,您可以使用Dictionary
,如果您只想过滤其他字段上的数据,您可以使用List
。最有效的方法是简单地自己循环集合并挑选出项目。 LINQ 几乎同样高效,但它增加了一点开销。另一方面,LINQ 代码变得非常简单。
使用 LINQ 扩展方法
Where
的示例:Using a DataTable would add quite a bit of overhead. It's easier to run a query once you set it up, because the code for it is already created, but it won't run as fast.
If you want to look up items using the
id
you can use aDictionary<Guid, AnonymousClient>
, if you only want to filter the data on the other fields you can just use aList<AnonymousClient>
.The most efficient would be to simply loop the collection yourself and pick out the items. LINQ is almost as efficient, but it adds a slight bit of overhead. On the other hand, the LINQ code gets very simple.
Example using the LINQ extension method
Where
:我会采用第一种方法。但你真的需要将它们存储在字典中吗?您已经收藏了它们,对吧?您可以使用 LINQ 来过滤集合本身。
等等...并构建您的过滤集合。
======更新======
这是使用城市进行过滤的更新查询:
如果您看到,第一部分基本上返回您的条件的布尔值,而不是字典您需要的对象。通过使用 ToDictionary 方法,您可以转换回字典。因此,现在执行 LINQ 后,您将拥有所有将城市设置为伦敦的 AnonymousClient。
I would go with the first approach. But do you really need to store them in Dictionary? You already have them in a collection right? you could use LINQ to filter on the collection itself.
etc.. and build your filtered collection.
======UPDATE======
Here is the updated query for filtering using city:
If you see, the first part basically returns you a boolean value for your condition and not the dictionary object that you need. By using the ToDictionary method, you convert back to a Dictionary. So, now after execution of the LINQ, you will have all AnonymousClient with city set to London.