1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; int [] fibNum = { 1, 1, 2, 3, 5, 8, 13, 21, 34 }; //num => num % 2 == 1, means get any number with modulo of 1 (AKA odd number) //in our case, its 1, 1, 3, 5, 13, 21. //Average() means add all of these numbers up and divide by how many there are // 1+1+3+5+13+21/6 = 7.333333 double averageValue = fibNum.Where(num => num % 2 == 1).Average(); Console.WriteLine(averageValue); |
Search for string in string array
lambda
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
string [] arr1 = new string[] { "otwone", "two", "threetwo", "fotwour", "five", "two" }; foreach (string s in arr1.Where( x => { if(x.Contains("two")) { return true; } return false; } )) Console.WriteLine(s); |
Result:
otwone
two
threetwo
fotwour
two
LinQ
1 2 3 4 5 6 7 8 9 10 |
string [] arr1 = new string[] { "otwone", "two", "threetwo", "fotwour", "five", "two" }; var query = from arr in arr1 where arr.Contains("two") select arr; foreach(var s in query) { Console.WriteLine("{0}", s); } |
Result:
otwone
two
threetwo
fotwour
two
Determine if any ints are larger or less
Lambda
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; foreach (int i in source.Where( x => { if (x <= 3) { Console.WriteLine("less than or equal to 3: {0}",x); return true; } else if (x >= 7) { Console.WriteLine("more than or equal to 7: {0}",x); return true; } return false; } )) Console.WriteLine(i); |
Result:
less than or equal to 3: 3
3
more than or equal to 7: 8
8
less than or equal to 3: 1
1
more than or equal to 7: 7
7
more than or equal to 7: 9
9
less than or equal to 3: 2
2
more than or equal to 7: 8
8
Find age in Array of Structs
linQ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
public class Program { struct Item { public int a; public string b; public Item(int a, string b) { this.a = a; this.b = b; } }; public static void Main() { Item [] people = { new Item( 12, "little todd" ), new Item( 13, "little timmy" ), new Item( 36, "Ricky"), new Item( 33, "zelda") }; var oldQuery = from person in people where (person.a >= 30) select person; foreach(var s in oldQuery) { Console.WriteLine("old person {0}", s.b); } } } |