How do you return certain properties from a linq query, rather than complete objects?
Asked Answered
W

2

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

Whiles answered 15/7, 2010 at 13:24 Comment(0)
S
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 }; 
Shalondashalt answered 15/7, 2010 at 13:25 Comment(7)
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? :)Whiles
Oh my God, this is absolutely sick! :)Whiles
LINQ is indeed groundbreaking. Just wait until you find out about LINQ to events. Then your mind will really start bending. :)Shalondashalt
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?Whiles
Oh I see, asynchronous programming. Tasty.Whiles
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.Shalondashalt
Thanks for the heads up Stephen, it's appreciated.Whiles
W
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.

Wesson answered 15/7, 2010 at 13:25 Comment(1)
Very interesting blog you've got there. Loved the article about slavery!Whiles

© 2022 - 2024 — McMap. All rights reserved.