2

If you have a Linq statement that uses a WHERE clause, for example:

var result = someCollection.Where(x => x.value > 5).Select(x => x);

Is the SELECT required, or is it redundant? It appears that I can safely omit the SELECT if I'm not trying to get at an object property, but am not sure if this is proper...

newmanth
  • 408
  • 7
  • 18

4 Answers4

4

In your case No, it is not required, since you are selecting the object. So you can have:

var result = someCollection.Where(x => x.value > 5);

as far as better practice is concerned, I would remove the redundant code.

But, if you are going to select a specific property then that could be useful, like:

var result = someCollection.Where(x => x.value > 5)
                   .Select(x=> x.SomeSpecificProperty);

One more thing to add, with query expression you will need the select.

var result = from x in someCollection
             where x.Value > 5
             select x;

but at compile time the above query expression will be converted to Method Expression, without Select.

Habib
  • 219,104
  • 29
  • 407
  • 436
  • 2
    Ah, I think that was where my confusion came from... that there is a difference between query and lambda syntax. Thanks. – newmanth Jul 08 '15 at 17:51
  • @newmanth, yes there is *only* the difference in syntax, otherwise query expression compiles into method expression. You can read more about it [here](http://stackoverflow.com/questions/15677958/difference-between-query-expression-and-method-expression-in-linq) – Habib Jul 08 '15 at 17:53
0

It's redundant. Select is more like the functional map (see JavaScript, Haskell, Ruby). If you aren't going to transform the input object into a different form than it is currently in, there's no need to use Select.

Dan
  • 10,282
  • 2
  • 37
  • 64
0

In Linq, is a SELECT required when WHERE is used?

No, it isnt.

maraaaaaaaa
  • 7,749
  • 2
  • 22
  • 37
0

No... is not necessary this time... may be if you want to select a new object different than "someCollection" it will be necessary

something like:

var result = someCollection.Where(x => x.value > 5).Select(x => new ObjName() { name = x.name, lastname = x.lastname });
lem2802
  • 1,152
  • 7
  • 18