Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addicted to LINQ [closed]

Tags:

.net

linq

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 :)

like image 833
Rob Avatar asked Nov 04 '08 15:11

Rob


2 Answers

One other observation; if you aren't using typed datasets, you might also want to know about the Field<> extension method:

    var customerOrderIds = table.Rows.Cast<DataRow>()
       .Where(x => x.Field<string>("CUSTOMER_ID") == customerId)
       .Select(x => x.Field<string>("CUSTOMER_ORDER_ID"))
       .Distinct();

Or using the query syntax:

   var customerOrderIds = (
        from row in table.Rows.Cast<DataRow>()
        where row.Field<string>("CUSTOMER_ID") == customerId
        select row.Field<string>("CUSTOMER_ORDER_ID")
     ).Distinct();

I'm not saying it is better or worse - just another viable option.

(Actually, I don't use DataTable very much, so YMMV)

like image 140
Marc Gravell Avatar answered Oct 16 '22 16:10

Marc Gravell


Seems good to me - although I'd try to use a strongly typed data set which makes the LINQ queries look even more pleasant.

But yes, LINQ is a very good thing - and LINQ to Objects (and the surrounding technologies for XML and DataSets) is fabulously predictable compared to the out-of-process LINQ providers. (It's less sexy than LINQ to SQL, but more widely applicable IMO.)

like image 20
Jon Skeet Avatar answered Oct 16 '22 15:10

Jon Skeet