Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda expression for Enumerable.Select

Tags:

c#

lambda

linq

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!

like image 840
eran otzap Avatar asked Dec 06 '22 19:12

eran otzap


1 Answers

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.
like image 103
dlev Avatar answered Dec 10 '22 02:12

dlev