Ok, the more I use LINQ, the more I like it! I recently found myself working in some legacy code at work. It is your classic DataSet and DataTable rich application. Well, when adding a bit of functionality I found myself really wanting to just query the rows of a DataTable for the results I was looking for.
Let me repeat that… instead of looping and adding to a temp collection, I just wanted to ask the Rows collection for what I needed. No looping, no temp variables, just give me what I want.
var customerOrderIds = table.Rows.Cast<DataRow>() .Where(x => (string)x['CUSTOMER_ID'] == customerId) .Select(x => (string)x['CUSTOMER_ORDER_ID']) .Distinct();
My question is whether or not this is a good thing, or am getting carried away with LINQ? It does seem to me that this declarative style of pulling a subset of data out of a collection is a good thing and more readable in the end. But then again, maybe I’m just smitten 🙂
One other observation; if you aren’t using typed datasets, you might also want to know about the
Field<>extension method:Or using the query syntax:
I’m not saying it is better or worse – just another viable option.
(Actually, I don’t use
DataTablevery much, so YMMV)