tags:

views:

88

answers:

2

Suppose I have:

 public class foobar
 {
    public int lorem;
    public int ipsum;
 }

 IEnumerable<foobar> items = new List<foobar>();
 items.add(new foobar(){lorem = 0, ipsum = 0};
 items.add(new foobar(){lorem = 1, ipsum = 1};

How can I get a IEnumerable of all "lorem" in "items" using Linq?

+4  A: 

Try the following

var allLorems = items.Select(x => x.lorem);
JaredPar
In what way is that "without using LINQ"? I'm more asking because it's been accepted than anything else...
Jon Skeet
@Jon: OP asked "using LINQ" not "without using LINQ"
Adam Robinson
Jon...looks like the original question was editted so that it now says 'using Linq' rather than 'without using Linq'.Confused me too.
Justin Niessner
ouch! I use that, how could I not see a so obvious solution?
Jader Dias
Justin: I'm glad it's not just me. I'm *sure* I saw it say "without using LINQ"!
Jon Skeet
And strictly speaking, the LINQ syntax would be (from x in items select x.lorem) but everybody calls the LINQ-supporting lambdas LINQ anyway ;)
Adam Robinson
"without using LINQ" was a typo, sorry, just corrected this
Jader Dias
Glad I didn't completely misread the question ;)
JaredPar
Jon: You're not the only one...almost posted the old foreach loop solution since he didn't want LINQ.
Justin Niessner
Adam: When you say "strictly speaking" can you provide details of this "strict" meaning of LINQ? LINQ is a fuzzy term, and always has been. I don't believe it's sensible to *only* include query expressions.
Jon Skeet
@Jon: My statement was more tonque-in-cheek as this is a pretty semantic distinction, but given what LINQ (as an acronym) stands for then I think it's entirely sensible to have a "stict" qualification for LINQ be that it's a query expression. Obviously it's convenient to refer to the usage of the lambdas that a LINQ query utilizes in its execution as LINQ, but I don't think it's entirely accurate. Nothing WRONG with it (again, purely semantic distinction), but nonetheless not 100% accurate.
Adam Robinson
+2  A: 

I think you mean:

 List<foobar> items = new List<foobar>();
 items.Add(new foobar(){lorem = 0, ipsum = 0});
 items.Add(new foobar(){lorem = 1, ipsum = 1});

and then:

var lorems=from i in items select i.lorem;
Sean
For a simple "single projection" or "single filter" I think it's clearer just to call the extension method, as per Jared's answer.
Jon Skeet
Maybe, but he asked for a answer using Linq!!!
Sean
+1 just to be persnickety. I stand by my comment, Jon ;)
Adam Robinson