tags:

views:

139

answers:

3

If I have a DataTable with a small or large amount of data, to select data from the datatable I can use the Datatable.Select() method or go for LINQ. Which one is faster and efficient?

A: 

If u want faster execution then Datatable.Select() or you can go for LINQ

Johnny
but that's what the OP said.
Matt Ellen
+4  A: 

Which one is best for your circumstance? Or, more importantly, does the speed difference for the amount of data you're querying make it worthwhile to choose one over the other?

LINQ is generally easier to read, on my opinion, than pretty much any other form of data filtering and has the advantage over using DataTable.Select of being, at least partially, strongly-typed making it harder to make mistakes.

// Using DataTable.Select()
DataRow[] records = myTable.Select("(MyIntField > 30 AND MyStringField == 'StringValue') OR AnotherField > 70");

// Using LINQ
var records = from record in myTable.AsEnumerable()
              where (record.Field<int>("MyIntField") > 30 
                     && Record.Field<string>("StringValue") == "StringValue") 
                    || 
                    (record.Field<int>("AnotherField") > 70)
              select record;

The LINQ query is bigger, but personally I think it's more readable

Rob
whill there any performance difference will be there if i use LINQ over Datatable.Select()?
Kishore Kumar
@Kishore, as I said, you'll really need to test that yourself. It's going to vary depending on **the amount of data you're returning** and **the complexity of the filter you're attempting to apply to the data**. If there is a peformance difference, it may be so small as to not be worth worrying about.
Rob
@Kishore: If you want performance above all, don't use either. Go low.
Steven Sudit
@Rob: You are missing closing quotes in the code in the second `StringValue`.
Shaihi
@Shaihi, thanks, fixed =)
Rob
A: 

Which one that will be the fastest only you can say.

  • List item
  • What's the amount of data?
  • How many records are returned?
  • How do you intent to use the result? E.g. will you always use every record in the result?
  • What's the complexity of the filter?

All those can impact which solution will be the fastest. As always if you do not have a performance problem don't optimize. If you do have a performance problem then use a profile to find out where to optimize.

If you do not have hard evidence that the select is a performance problem go for readability. That in my mind translate into the LINQ solution

Rune FS