Select every second element from array using lambda [duplicate] - c#

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

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]

C# Loop Array Index Values back to Beginning of Array once out of Index

I am looking to create a program like the following (c# btw):
int[] arr = new int[9]
//some code that puts values 1, 0, or 2 in each array element
for(int i = 0; i < arr.Length; i++)
{
if (arr[i] == arr[i + 3]) { return true; }
}
So, for each value in the array I am applying a formula that does something with that value and the value 3 indexes ahead of it. Of course, this runs into an out of range exception once i+3>8.
What I'd like to do is if the the desired index is out of range then loop the index values back around to the beginning of the array. So, in an array of length 9 where the last index is 8, if on a given loop i = 7, and i+3 then = 10, I would like i+3 to 'become,' by whatever means, 1, and then when i = 8, and i+3 = 11, I want i+3 to become 2.
So, the index pairs being evaluated would be something like:
i , i+3
0 3
1 4
2 5
3 6
4 7
5 8
6 0
7 1
8 2
how can I go about doing this?
Thanks for any help.
Use the modulo operator like this:
if (arr[i] == arr[(i + 3) % arr.Length]) { return true; }
You could try the following expression inside your if statement.
arr[i] == arr[(i + 3) % arr.Length];
The % Operator
Divides the value of one expression by the value of another, and
returns the remainder.

How to Type it in LINQ?

i am learning C# and LINQ so i am sorry for that question.
how to type in linq to group the same elements in certain array, but when they group it they see if the count of the group is greater than 2 and then division it by 2 and return the value of the group count and then add it to int
what i want the linq to do in code :
s => s > 2
s /= 2
return s;
my original code is that:
int n = Convert.ToInt32(Console.ReadLine());
string[] userinput = Console.ReadLine().Split(' ');
int[] socks = new int[n];
socks = Array.ConvertAll(userinput, Int32.Parse);
var result = socks.GroupBy(s => s > 2).ToArray(); //This is the line which i want help
int total = 0;
foreach (var group in result)
{
total += group.Count();
Console.WriteLine(group.Count());
}
Lets assume we have 10 kinds of socks. which are 10,20,30,40,50,60,70, 80,90,100
now in the first line i enter the number of the socks i have so for example its 5.
in the second line i enter the 5 socks kinds for example. 10 10 20 20 30
now i want the linq code to define that there is 3 keys here which are 10 20 30, the 10 key has more than only 1 count it has 2. the same for 20 but the 30 only have 1 so lets forget about the 30. now the count of they key of each one of them is 2 so lets divide it by 2 for each one then add the divided number to the total so 2/2 for each one equals 1 so total = 2 (this is the my expected output)
If understand you right, you want to count pairs of socks:
int total = socks
.GroupBy(x => x)
.Sum(chunk => chunk.Count() / 2);
According to your example:
[10, 10, 20, 20, 30]
after grouping socks by their sizes
10: [10, 10] - 2 socks, 1 pair (you've put it as "divide by 2")
20: [20, 20] - 2 socks, 1 pair
30: [30] - 1 sock, 0 pairs
-------------------------------
2 pairs in total (the expected value)
My example (from the comments to the question)
1, 2, 2, 2, 3, 4, 5, 5
should return 2 as well (we have 2 pairs: of size 2 and 5)
In case you want to get pairs:
var pairs = socks
.GroupBy(x => x)
.Select(chunk => new {
size = chunk.Key,
count = chunk.Count() / 2, });
//.Where(pair => pair.count > 0); // you may want to filter out single socks

C# Using Bool, how to check a double is truly divisible by another number? [duplicate]

This question already has answers here:
How can I calculate divide and modulo for integers in C#?
(5 answers)
Closed 7 years ago.
Is there a way of checking that a value is wholly divisible by another number, for example 1000 divided by 100 would be true, but 1115 divided by 100 would be false?
I am tring to
Any help would be much appreciated :-)
You can use the %-operator:
bool isDivisible = 1115 % 100 == 0;
The % operator computes the remainder after dividing its first operand
by its second. All numeric types have predefined remainder operators.
Check out % operator. 1000 % 100 yields 0. 1115 % 100 yields 15
You can use mod operator (%) and check that remainder is equal to 0:
var result = (1000.00 % 100) == 0; // evaluates to true
var result = (1115.00 % 100) == 0; // evaluates to false

Where(i => i % 2 == 0)

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

Categories

Resources