Reputation: 12533
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
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:
foreach
loop, or call .ToList()
, .ToArray()
etc.Upvotes: 15