5

I've just downloaded the Linq provider for NHibernate and am just a little excited. But I don't know Linq syntax that well.

I can return whole objects from a query like this:

var query = from foo in session.Linq<Kctc.BusinessLayer.Domain.Case>()
                  where foo.CaseNumber > 0
                  select foo;

And I can select a single property like this:

var query = from foo in session.Linq<Kctc.BusinessLayer.Domain.Case>()
                  where foo.CaseNumber > 0
                  select foo.Id;

But how would I select two properties, e.g. foo.Id and foo.Bar? Or is that not possible?

Thanks

David

David
  • 15,750
  • 22
  • 90
  • 150

2 Answers2

8

Use an anonymous projection:

var query = from foo in session.Linq<Kctc.BusinessLayer.Domain.Case>() 
              where foo.CaseNumber > 0 
              select new { foo.Id, foo.Bar }; 
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • Thanks to both Stephen and ck. I am so excited about this Linq business. It's the most exciting thing Ive found since jQuery. Why did it take me so long? :) – David Jul 15 '10 at 13:27
  • Oh my God, this is absolutely sick! :) – David Jul 15 '10 at 13:29
  • 1
    LINQ is indeed groundbreaking. Just wait until you find out about [LINQ to events](http://blogs.msdn.com/b/rxteam/archive/2010/07/07/rx-hands-on-labs-published.aspx). Then your mind will *really* start bending. :) – Stephen Cleary Jul 15 '10 at 13:33
  • The page you linked to doesn't contain any mention of linq, or events (not in the programming context anyway). What is Linq to events? – David Jul 15 '10 at 13:47
  • Oh I see, asynchronous programming. Tasty. – David Jul 15 '10 at 13:57
  • That blog entry has a link to a PDF download. It's a gentle introduction to the Rx extensions library, which is nearing completion by Microsoft Research. The term "LINQ to events" refers to the underlying concept of the library: to treat asynchronous events (e.g., mouse move events) as a sequence of *data*. Once this conceptual leap is made, it's natural to use them in LINQ expressions, and this is exactly what Rx enables. Read the hands-on-lab for .NET for all the fun details. – Stephen Cleary Jul 15 '10 at 13:58
  • Thanks for the heads up Stephen, it's appreciated. – David Jul 16 '10 at 08:45
1

You have to create a new Anonymous type, that will only be available in the current scope (i.e. it can't be returned from a method etc.)

var query = from foo in session.Linq<Kctc.BusinessLayer.Domain.Case>() 
              where foo.CaseNumber > 0 
              select new { foo.Id, foo.Bar }; 

Or you can create a custom class and populate that.

cjk
  • 45,739
  • 9
  • 81
  • 112