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?
views:
139answers:
3If u want faster execution then Datatable.Select() or you can go for LINQ
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
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