Free Newsletters

   All InfoWorld Newsletters
Strategic Developer | Martin Heller » A Working Distinct LINQ Query in C#

January 30, 2008 | Comments: (0)

A Working Distinct LINQ Query in C#

As I mentioned Monday and in my Visual Studio 2008 review, I've been struggling with the finer points of LINQ queries. In a talkback comment to my review, "CSharper" pointed me at one solution to finding the LINQ equivalent of a SQL "SELECT DISTINCT" query: tack on a LINQ .Distinct() method call to the query, which needs to be enclosed in parentheses.

That worked, but it destroyed the sort order created by a previous orderby clause. Obviously, I also had to learn to use the LINQ .OrderBy() method so that I could apply the sort after the sift. That was a little harder, since .OrderBy() takes a lambda expression, and I wasn't yet familiar with that new C# syntax.

Nevertheless, I got it working. It isn't beautiful, but this is really version 1.0 of LINQ.

var qAV = (from ai in db.AppInfos
   join acai in db.AppCatAIs on ai.Prodid equals acai.Prodid
   join ac in db.AppCategories on acai.acatid equals ac.acatid
   where ac.Category == category1 || ac.Category == category2
   select ai)
     .Distinct()
     .OrderBy(n => n.ProductName);

Posted by Martin Heller on January 30, 2008 08:18 AM


RATE THIS ARTICLE:





 

  •  
  • COMMENTS




...and this is easier than SQL in what way?

Posted by: dj at January 31, 2008 10:25 AM

dj,

That's my question too. I fail to see where LINQ is more efficient or less confusing than using stored procedures.

Posted by: kbiel at January 31, 2008 12:28 PM

I think the advantage of LINQ is that all the schema and types can be checked at compile time, versus a typical approach where most of the checking would happen at run time (if at all). Also, since Visual Studio knows the LINQ syntax it can help you with Intellisense for example.

SQL still seems more natural to me, and of course it is supported in a lot more environments than LINQ--like the ones I actually use.

Posted by: Dave at February 1, 2008 07:16 AM

It is very complicated, it is simply easier from my point of view to use Stored Procs or Views.

Posted by: Michael at February 7, 2008 10:43 AM

I think LINQ to SQL is overrated, due to the aboce ugliness and most devs already being familiar with SQL. I'm hoping in the next version and in LINQ to Entities they can improve it.

But LING to Objects is great, using LINQ against in memory objects, List<> and what not is great, fast and simple.

Posted by: biaachmonkie at March 17, 2008 05:36 PM

Technology White Papers

 

InfoWorld Technology Marketplace

» Technology White Papers Library

Technology White Papers by Topic

Technology White Papers E-mail Alert

Find out when the latest white paper is available:
 
 
» BUY A LINK NOW

Sponsored Technology Links