开发者

Which is better? DataTable.Select() or Linq for filtering objects?

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 -

  1. Storing it in a dictionary Dictionary<Guid, AnonymousClient> and using Linq to filter the objects.
  2. 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?


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 a Dictionary<Guid, AnonymousClient>, if you only want to filter the data on the other fields you can just use a List<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:

var companies = clients.Where(c => c.category == "Company");


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.

var cityFiltered = from p in AnonymousClientList where p.city == 'London' select p;

etc.. and build your filtered collection.

======UPDATE======

Here is the updated query for filtering using city:

var filtered = (from c in clients where c.Value.city=="London" select c).ToDictionary(x => x.Key, x => x.Value);

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜