eran otzap
eran otzap

Reputation: 12533

lambda expression for Enumerable.Select

I'm trying to figure out how to start using linq and lambda expressions.

First of all, if someone could direct me to some good tutorials it will be most appreciated.

Secondly:

I'm trying to select all values which are equal to a specific value using Select method.

I have noticed that select could be defined with a

Select<TSource,TResult>(...lambda expression...)  

Now for this purpose I want to select all the numbers which are equal to 5.

int[] numbers = { 1, 2, 3, 4, 5, 5, 5, 6, 7, 8 };
IEnumerable<int> res = numbers.Select( x=>5 );    

This does not work, I just don't understand how this works. And in what situation should I define TSource and TResult, and what would they be in this case?

Thanks in advance!

Upvotes: 4

Views: 22696

Answers (1)

dlev
dlev

Reputation: 48596

Select() is used to project each member of the old sequence into a new member of a new sequence. To filter, you use Where():

var evens = numbers.Where(x => x % 2 == 0);
var theFiveSequence = numbers.Where(x => x == 5);

An example of using Select() might be multiplying each number by two:

var doubledNumbers = numbers.Select(x => 2*x);

You can combine those methods together, too:

var doubledNumbersLessThanTen = numbers.Select(x => 2*x).Where(x < 10);

Two important things to remember about LINQ:

  1. The elements of the base sequence are (almost always) not modified. You create new sequences from old sequences.
  2. The queries you write are lazily evaluated. You won't get results from them until you use them in a foreach loop, or call .ToList(), .ToArray() etc.

Upvotes: 15

Related Questions