Where(i => i % 2 == 0) - c#

I'm currently learning about PLINQ (Parallel Language Integrated Query) on Visual Studio 2012's C#.
In the one lesson Where(i => i % 2 == 0) was given to me, but I've no idea what it means and the book i'm studying from didn't give any explanation.
Does anyone know what this means?

First hope you know % which is "The % operator computes the remainder after dividing its first operand by its second". Read more about % Operator
if you have a list of numbers
var list = new List<Int32>() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var result = list.Where(i => i%2 == 0);
So the result will have 2,4,6,8 and 10.
Same thing can be written as
var ans = new List<Int32>();
foreach (var an in list)
{
if (an%2 == 0)
ans.Add(an);
}

The query is selecting only even numbers, where division by 2 has no remainder.
The % operator computes the remainder after dividing its first
operand by its second. All numeric types have predefined remainder
operators.
http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx

lambda expressions are a bit weird at 1st however when you experiment a bit in VS (and its intellisense) you'll get used to it in no time. as soon as you type in "i=>" you declare a range variable of your type of object which implements IEnumerable(<T>) interface. In this case i is one element of your list (or other IEnumerable>> list, dictionary....) to investigate this case you search for even numbers...

Let's say this is the case:
List<int> source = new List<int>() { 1, 2, 3, 4 };
var evenNumbers = source.Where(i => i % 2 == 0);
Where is filtering source and returning only it's even numbers.
Where is a Linq extension method that works on any object implementing the IEnumerable interface (likeList).
i => i % 2 == 0 is a lambda expression. In this case it means that for each item i in source, Where will apply the expression i % 2 == 0.
Where selects the items in source for which the lambda expression is true. In this case, the expression is true when i is an even number.
This is because of the modulo operator %, which returns the remainder of the integer division between two numbers a and b: a % b. If a = 4 and b = 3, then a % b values 1, because it is what remains when dividing 4 by 3. If % returns 0, then it means that a is divided by b. If b is 2, then it means that a is even.

Where(i => i % 2 == 0)
it means i goes to where i % 2 == 0 that is if
you are doing it for a list of integer it will return all even numbers from list

Related

Clarify what select does

I haven't been able to find anything on google.
I have this piece of code:
Random r = new Random();
int[] output = Enumerable.Range(0, 11).Select(x => x / 2).OrderBy(x => r.Next()).ToArray();
and I am having trouble actually understanding what each element does.
It generates a range of numbers and elements between 0 and 11.
But what does the select(x => x / 2) do ? does it just make pairs of elements,
I know what the whole thing spits out, an array with pairs of numbers, with a single number which has no pair.
but it is a bit above me to fully understand it ?
( is this even okay to ask on here ?? or should I delete the question again ? )
It generates a range of numbers and elements between 0 and 11. But what does the select(x => x / 2) do ? does it just make pairs of elements.
No, Select does what in some programming languages is known as map. It is called on an IEnumerable<T> and has as parameter Func<T,U> a function, and it produces an IEnumerable<U> where each element if the given IEnumerable<T> is processes through the function and the result is emitted in the result.
So in this case, it will take a range from 0 to (excluding) 11, and for each of those integers, perform an integer divsion by two:
csharp> Enumerable.Range(0, 11);
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
csharp> Enumerable.Range(0, 11).Select(x => x/2);
{ 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5 }
Since:
{ 0/2, 1/2, 2/2, 3/2, 4/2, 5/2, 6/2, 7/2, 8/2, 9/2, 10/2 }
== { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5 }
Later then that IEnumerable<int> is reordered (using the OrderBy) by using pseudo-random numbers (so we shuffle them) and converted into a list.
.Range(0, 11) // generate a sequence of integers starting at 0 and incrementing 11 times (i.e. the values 0 up to and including 10)
.Select(x => x / 2) // divide each of those values from previous result by 2 and return them
.OrderBy(x => r.Next()) // then order them randomly using a random number
.ToArray(); // return the end result as an array
Think of Select as doing a transformation to each element of the IEnumerable.
For example, let's say we have a list like this:
0 1 2 3 4 5 6 7 8 9 10
Then we call .Select(x => x / 2), we are saying that for each element x in the list, do the following transformation:
x / 2
We divide each element in the list by two:
Original Transformation Result
0 0 / 2 0
1 1 / 2 0
2 2 / 2 1
3 3 / 2 1
4 4 / 2 2
5 5 / 2 2
6 6 / 2 3
7 7 / 2 3
8 8 / 2 4
9 9 / 2 4
10 10 / 2 5
We get
0 0 1 1 2 2 3 3 4 4 5 5
What Select() does is that it evaluates the given expression for every element of the Enumerable it's called on (the original list), and returns a new Enumerable with the results.
For a list:
[2, 4, 6]
it's going to return:
[2/2, 4/2, 6/2]
where / means "division", so the result of the Select() (not the entire LINQ chain) will be:
[1, 2, 3]
Analogously, if your source list is:
words = ["dog", "child", "building"]
And you call:
words.Select(word => word.Length)
you get a list of all the lengths of the strings in the list in order:
[3, 5, 7]

Accurate behavior of the sort method in C#?

static void Main()
{
var array = new[] {1, 2, 3, 4, 5};
Array.Sort(array, (x, y) => x % 2 == y % 2 ? 0 : x % 2 == 1 ? -1 : 1);
array.ToList().ForEach(Console.WriteLine);
}
The output result is 3,5,1,2,4.
According to my understanding, in the sort delegate: Odd numbers equal odd numbers; Even number equal even numbers; Odd numbers are before even numbers. Why the output is not 1,3,5,2,4? Thanks.
From MSDN:
Array.Sort uses the QuickSort algorithm. This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.
You are just comparing even and odd in your comparer function. Like the others said, quicksort is non-stable. Why not add an additional check for value in addition to even/odd when the values are both either even or odd.
// if x odd and y even return -1
// else if x even and y odd return 1
// else return x.CompareTo(y)
Array.Sort(array, (x, y) => x % 2 == y % 2 ? x.CompareTo(y) : x % 2 > y % 2 ? -1 : 1);

Select every second element from array using lambda [duplicate]

This question already has answers here:
How can I get every nth item from a List<T>?
(10 answers)
Closed 8 years ago.
C# 4.0. How can the following be done using lambda expressions?
int[] a = new int[8] { 0, 1, 2, 3, 4, 5, 6, 7 };
// Now fetch every second element so that we get { 0, 2, 4, 6 }
int[] list = a.Where((value, index) => index % 2 == 0)
.ToArray();
It will only select even indexes, as calculate by the % (mod) operator .
5 % 2 // returns 1
4 % 2 // returns 0
According to MSDN:
% Operator
Another approach using Enumerable.Range
var result = Enumerable.Range(0, a.Length/2)
.Select(i => a[2*i])
.ToArray();
Or use bitwise for more efficient to check even:
var result = a.Where((i, index) => (index & 1) == 0)
.ToArray();
The remainder operator is your friend.
int[] everySecond = a.Where((i, ind) => ind % 2 == 0).ToArray();
% Operator (C# Reference)
The % operator computes the remainder after dividing its first operand
by its second. All numeric types have predefined remainder operators.
E.Lippert: What's the difference? Remainder vs Modulus

Custom order by, is it possible?

I have the following collection:
-3, -2, -1, 0, 1, 2, 3
How can I in a single order by statement sort them in the following form:
The negative numbers are sorted first by their (absolute value) then the positive numbers.
-1, -2, -3, 0, 1, 2, 3
Combination sorting, first by the sign, then by the absolute value:
list.OrderBy(x => Math.Sign(x)).ThenBy(x => Math.Abs(x));
or:
from x in list
orderby Math.Sign(x), Math.Abs(x)
select x;
This is conceptually similar to the SQL statement:
SELECT x
FROM list
ORDER BY SIGN(x), ABS(x)
In LINQ-to-Objects, the sort is performed only once, not twice.
WARNING: Math.Abs(x) will fail if x == int.MinValue. If this marginal case is important, then you have to handle it separately.
var numbers = new[] { -3, -2, -1, 0, 1, 2, 3 };
var customSorted = numbers.OrderBy(n => n < 0 ? int.MinValue - n : n);
The idea here is to compare non-negative numbers by the value they have. And compare negative numbers with the value int.MinValue - n which is -2147483648 - n and because n is negative, the higher negative number we, the lower negative result the outcome will be.
It doesn't work when the list itself contains the number int.MinValue because this evaluates to 0 which would be equal to 0 itself. As Richard propose it could be made with longĀ“s if you need the full range but the performance will be slightly impaired by this.
Try something like (VB.Net example)
Orderby(Function(x) iif(x<0, Math.Abs(x), x*1000))
...if the values are <1000
You could express it in LINQ, but if I were reading the code two years later, I'd prefer to see something like:
list.OrderBy(i=>i, new NegativeThenPositiveByAscendingAbsoluteValueComparer());
You will need to implement IComparer.

How to find multiple in C#

how might I find out, in an if statement, weather the specified int is a multiple of 5? This is what I mean:
if(X [is a multiple of] 5)
{
Console.Writeline("Yes");
}
What would be [is a multiple of]?
Also, why is it that when I do:
if(X = 5)
{
Console.Writeline("sdjfdslf");
}
it shows "X = 5" in red and tells me "Can not implicitly convert type "int" to "bool"? I am using X as an input.
how might I find out, in an if statement, weather the specified int is a multiple of 5?
You want to use the modulo operation (%).
if (X % 5 == 0) {
Console.Writeline("Yes");
}
it shows "X = 5" in red and tells me "Can not implicitly convert type "int" to "bool"? I am using X as an input.
The single equals = is assignment. You want the double equals == to do a check for equality.
if (x % 5 == 0) Console.WriteLine("yes");
C# mod operator
Also use == to return a boolean value for a comparison.
You can use the modulus operator (%), which returns the remainder after division:
if (X % 5 == 0) { Console.Writeline("Yes"); }
You're looking for the modulo operator (%) to determine if an integer is a multiple of another integer, like so:
if (x % 5 == 0)
To answer the second part of your question (if (x = 5)), a single equals sign is an assignment operator in C#. You should be using the double equals sign instead, which is the comparison operator, like so: if (x == 5).
= is the assignment operator, while == is used for comparison.
So when your write if (X = 5), you're assigning 5 to X and treat that as a boolean expression.
Interestingly, assigning a value to a variable also returns the value itself.
y = x = 5
assigns 5 to x and assigns the result of (x = 5), which is also 5, to y.

Categories

Resources