9866550012
CSHARP LINQ EXAMPLESThis sample uses where to find all elements of an array less than 5.
public void Linq1() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = from n in numbers where n < 5 select n; Console.WriteLine("Numbers < 5:"); foreach (var x in lowNums) { Console.WriteLine(x); } }
Result
Numbers < 5:
4
1
3
2
0This sample uses group by to partition a list of numbers by their remainder when divided by 5.
public void Linq40() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var numberGroups = from n in numbers group n by n % 5 into g select new { Remainder = g.Key, Numbers = g }; foreach (var g in numberGroups) { Console.WriteLine("Numbers with a remainder of {0} when divided by 5:", g.Remainder); foreach (var n in g.Numbers) { Console.WriteLine(n); } } }
Result
Numbers with a remainder of 0 when divided by 5:
5
0
Numbers with a remainder of 4 when divided by 5:
4
9
Numbers with a remainder of 1 when divided by 5:
1
6
Numbers with a remainder of 3 when divided by 5:
3
8
Numbers with a remainder of 2 when divided by 5:
7
2
5
0
Numbers with a remainder of 4 when divided by 5:
4
9
Numbers with a remainder of 1 when divided by 5:
1
6
Numbers with a remainder of 3 when divided by 5:
3
8
Numbers with a remainder of 2 when divided by 5:
7
2
public void Linq41() { string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" }; var wordGroups = from w in words group w by w[0] into g select new { FirstLetter = g.Key, Words = g }; foreach (var g in wordGroups) { Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter); foreach (var w in g.Words) { Console.WriteLine(w); } } }
Result
Words that start with the letter 'b':
blueberry
banana
Words that start with the letter 'c':
chimpanzee
cheese
Words that start with the letter 'a':
abacus
apple
blueberry
banana
Words that start with the letter 'c':
chimpanzee
cheese
Words that start with the letter 'a':
abacus
apple
public void Linq73() { int[] factorsOf300 = { 2, 2, 3, 5, 5 }; int uniqueFactors = factorsOf300.Distinct().Count(); Console.WriteLine("There are {0} unique factors of 300.", uniqueFactors); }
Result
There are 3 unique factors of 300.
public void Linq74() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int oddNumbers = numbers.Count(n => n % 2 == 1); Console.WriteLine("There are {0} odd numbers in the list.", oddNumbers); }
Result
There are 5 odd numbers in the list.This sample uses Sum to get the total of the numbers in an array.
public void Linq79() { string[] words = { "cherry", "apple", "blueberry" }; double totalChars = words.Sum(w => w.Length); Console.WriteLine("There are a total of {0} characters in these words.", totalChars); }
Result
There are a total of 20 characters in these words.This sample uses Min to get the lowest number in an array.
public void Linq82() { string[] words = { "cherry", "apple", "blueberry" }; int shortestWord = words.Min(w => w.Length); Console.WriteLine("The shortest word is {0} characters long.", shortestWord); }
Result
The shortest word is 5 characters long.This sample uses Max to get the highest number in an array.
public void Linq86() { string[] words = { "cherry", "apple", "blueberry" }; int longestLength = words.Max(w => w.Length); Console.WriteLine("The longest word is {0} characters long.", longestLength); }
Result
The longest word is 9 characters long.This sample uses Average to get the average of all numbers in an array.
public void Linq89() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; double averageNum = numbers.Average(); Console.WriteLine("The average number is {0}.", averageNum); }
Result
The average number is 4.5.This sample uses Average to get the average length of the words in the array.
public void Linq90() { string[] words = { "cherry", "apple", "blueberry" }; double averageLength = words.Average(w => w.Length); Console.WriteLine("The average word length is {0} characters.", averageLength); }
Result
The average word length is 6.66666666666667 characters.
public void Linq92() { double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 }; double product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor); Console.WriteLine("Total product of all numbers: {0}", product); }
Result
Total product of all numbers: 88.33081This sample uses Aggregate to create a running account balance that subtracts each withdrawal from the initial balance of 100, as long as the balance never drops below 0.
public void Linq93() { double startBalance = 100.0; int[] attemptedWithdrawals = { 20, 10, 40, 50, 10, 70, 30 }; double endBalance = attemptedWithdrawals.Aggregate(startBalance, (balance, nextWithdrawal) => ((nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance)); Console.WriteLine("Ending balance: {0}", endBalance); }
Result
Ending balance: 20This sample uses select to produce a sequence of ints one higher than those in an existing array of ints.
public void Linq6() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var numsPlusOne = from n in numbers select n + 1; Console.WriteLine("Numbers + 1:"); foreach (var i in numsPlusOne) { Console.WriteLine(i); } }
Result
Numbers + 1:
6
5
2
4
10
9
7
8
3
1
6
5
2
4
10
9
7
8
3
1
This sample uses select to produce a sequence of strings representing the text version of a sequence of ints.
public void Linq8() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; var textNums = from n in numbers select strings[n]; Console.WriteLine("Number strings:"); foreach (var s in textNums) { Console.WriteLine(s); } }
Result
Number strings:
five
four
one
three
nine
eight
six
seven
two
zero
five
four
one
three
nine
eight
six
seven
two
zero
This sample uses select to produce a sequence of the uppercase and lowercase versions of each word in the original array.
public void Linq9() { string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" }; var upperLowerWords = from w in words select new { Upper = w.ToUpper(), Lower = w.ToLower() }; foreach (var ul in upperLowerWords) { Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower); } }
Result
Uppercase: APPLE, Lowercase: apple
Uppercase: BLUEBERRY, Lowercase: blueberry
Uppercase: CHERRY, Lowercase: cherry
Uppercase: BLUEBERRY, Lowercase: blueberry
Uppercase: CHERRY, Lowercase: cherry
This sample uses select to produce a sequence containing text representations of digits and whether their length is even or odd.
public void Linq10() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; var digitOddEvens = from n in numbers select new { Digit = strings[n], Even = (n % 2 == 0) }; foreach (var d in digitOddEvens) { Console.WriteLine("The digit {0} is {1}.", d.Digit, d.Even ? "even" : "odd"); } }
Result
The digit five is odd.
The digit four is even.
The digit one is odd.
The digit three is odd.
The digit nine is odd.
The digit eight is even.
The digit six is even.
The digit seven is odd.
The digit two is even.
The digit zero is even.
The digit four is even.
The digit one is odd.
The digit three is odd.
The digit nine is odd.
The digit eight is even.
The digit six is even.
The digit seven is odd.
The digit two is even.
The digit zero is even.
This sample uses an indexed Select clause to determine if the value of ints in an array match their position in the array.
public void Linq12() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var numsInPlace = numbers.Select((num, index) => new { Num = num, InPlace = (num == index) }); Console.WriteLine("Number: In-place?"); foreach (var n in numsInPlace) { Console.WriteLine("{0}: {1}", n.Num, n.InPlace); } }
Number: In-place?
5: False
4: False
1: False
3: True
9: False
8: False
6: True
7: True
2: False
0: False
5: False
4: False
1: False
3: True
9: False
8: False
6: True
7: True
2: False
0: False
This sample combines select and where to make a simple query that returns the text form of each digit less than 5.
public void Linq13() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; var lowNums = from n in numbers where n < 5 select digits[n]; Console.WriteLine("Numbers < 5:"); foreach (var num in lowNums) { Console.WriteLine(num); } }
Result
Numbers < 5:
four
one
three
two
zero
four
one
three
two
zero
This sample uses a compound from clause to make a query that returns all pairs of numbers from both arrays such that the number from numbersA is less than the number from numbersB.
public void Linq14() { int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var pairs = from a in numbersA from b in numbersB where a < b select new { a, b }; Console.WriteLine("Pairs where a < b:"); foreach (var pair in pairs) { Console.WriteLine("{0} is less than {1}", pair.a, pair.b); } }
Result
Pairs where a < b:
0 is less than 1
0 is less than 3
0 is less than 5
0 is less than 7
0 is less than 8
2 is less than 3
2 is less than 5
2 is less than 7
2 is less than 8
4 is less than 5
4 is less than 7
4 is less than 8
5 is less than 7
5 is less than 8
6 is less than 7
6 is less than 8
0 is less than 1
0 is less than 3
0 is less than 5
0 is less than 7
0 is less than 8
2 is less than 3
2 is less than 5
2 is less than 7
2 is less than 8
4 is less than 5
4 is less than 7
4 is less than 8
5 is less than 7
5 is less than 8
6 is less than 7
6 is less than 8
This sample uses Distinct to remove duplicate elements in a sequence of factors of 300.
public void Linq46() { int[] factorsOf300 = { 2, 2, 3, 5, 5 }; var uniqueFactors = factorsOf300.Distinct(); Console.WriteLine("Prime factors of 300:"); foreach (var f in uniqueFactors) { Console.WriteLine(f); } }
Result
Prime factors of 300:
2
3
5
2
3
5
This sample uses Union to create one sequence that contains the unique values from both arrays.
public void Linq48() { int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var uniqueNumbers = numbersA.Union(numbersB); Console.WriteLine("Unique numbers from both arrays:"); foreach (var n in uniqueNumbers) { Console.WriteLine(n); } }
Result
Unique numbers from both arrays:
0
2
4
5
6
8
9
1
3
7
0
2
4
5
6
8
9
1
3
7
This sample uses Intersect to create one sequence that contains the common values shared by both arrays.
public void Linq50() { int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var commonNumbers = numbersA.Intersect(numbersB); Console.WriteLine("Common numbers shared by both arrays:"); foreach (var n in commonNumbers) { Console.WriteLine(n); } }
Result
Common numbers shared by both arrays:
5
8
5
8
This sample uses Except to create a sequence that contains the values from numbersAthat are not also in numbersB.
public void Linq52() { int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB); Console.WriteLine("Numbers in first array but not second array:"); foreach (var n in aOnlyNumbers) { Console.WriteLine(n); } }
Result
Numbers in first array but not second array:
0
2
4
6
9
0
2
4
6
9
This sample uses ToArray to immediately evaluate a sequence into an array.
public void Linq54() { double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 }; var sortedDoubles = from d in doubles orderby d descending select d; var doublesArray = sortedDoubles.ToArray(); Console.WriteLine("Every other double from highest to lowest:"); for (int d = 0; d < doublesArray.Length; d += 2) { Console.WriteLine(doublesArray[d]); } }
Result
Every other double from highest to lowest:
4.1
2.3
1.7
4.1
2.3
1.7
public void Linq55() { string[] words = { "cherry", "apple", "blueberry" }; var sortedWords = from w in words orderby w select w; var wordList = sortedWords.ToList(); Console.WriteLine("The sorted word list:"); foreach (var w in wordList) { Console.WriteLine(w); } }
Result
The sorted word list:
apple
blueberry
cherry
apple
blueberry
cherry
This sample uses ToDictionary to immediately evaluate a sequence and a related key expression into a dictionary.
public void Linq56() { var scoreRecords = new[] { new {Name = "Alice", Score = 50}, new {Name = "Bob" , Score = 40}, new {Name = "Cathy", Score = 45} }; var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name); Console.WriteLine("Bob's score: {0}", scoreRecordsDict["Bob"]); }
Result
Bob's score: { Name = Bob, Score = 40 }
This sample uses OfType to return only the elements of the array that are of type double.
public void Linq57() { object[] numbers = { null, 1.0, "two", 3, "four", 5, "six", 7.0 }; var doubles = numbers.OfType<double>(); Console.WriteLine("Numbers stored as doubles:"); foreach (var d in doubles) { Console.WriteLine(d); } }
Result
Numbers stored as doubles:
1
7
1
7
This sample uses Take to get only the first 3 elements of the array.
public void Linq20() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var first3Numbers = numbers.Take(3); Console.WriteLine("First 3 numbers:"); foreach (var n in first3Numbers) { Console.WriteLine(n); } }
Result
First 3 numbers:
5
4
1This sample uses Skip to get all but the first 4 elements of the array.
public void Linq22() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var allButFirst4Numbers = numbers.Skip(4); Console.WriteLine("All but first 4 numbers:"); foreach (var n in allButFirst4Numbers) { Console.WriteLine(n); } }
Result
All but first 4 numbers:
9
8
6
7
2
0This sample uses TakeWhile to return elements starting from the beginning of the array until a number is hit that is not less than 6.
public void Linq24() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6); Console.WriteLine("First numbers less than 6:"); foreach (var n in firstNumbersLessThan6) { Console.WriteLine(n); } }
Result
First numbers less than 6:
5
4
1
3
5
4
1
3
This sample uses TakeWhile to return elements starting from the beginning of the array until a number is hit that is less than its position in the array.
public void Linq25() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var firstSmallNumbers = numbers.TakeWhile((n, index) => n >= index); Console.WriteLine("First numbers not less than their position:"); foreach (var n in firstSmallNumbers) { Console.WriteLine(n); } }
Result
First numbers not less than their position:
5
4This sample uses SkipWhile to get the elements of the array starting from the first element divisible by 3.
public void Linq26() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var allButFirst3Numbers = numbers.SkipWhile(n => n % 3 != 0); Console.WriteLine("All elements starting from first element divisible by 3:"); foreach (var n in allButFirst3Numbers) { Console.WriteLine(n); } }
Result
All elements starting from first element divisible by 3:
3
9
8
6
7
2
0
3
9
8
6
7
2
0
This sample uses SkipWhile to get the elements of the array starting from the first element less than its position.
public void Linq27() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var laterNumbers = numbers.SkipWhile((n, index) => n >= index); Console.WriteLine("All elements starting from first element less than its position:"); foreach (var n in laterNumbers) { Console.WriteLine(n); } }
Result
All elements starting from first element less than its position:
1
3
9
8
6
7
2
0
1
3
9
8
6
7
2
0
This sample uses First to find the first element in the array that starts with 'o'.
public void Linq59() { string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; string startsWithO = strings.First(s => s[0] == 'o'); Console.WriteLine("A string starting with 'o': {0}", startsWithO); }
Result
A string starting with 'o': one
This sample uses FirstOrDefault to try to return the first element of the sequence, unless there are no elements, in which case the default value for that type is returned.
public void Linq61() { int[] numbers = { }; int firstNumOrDefault = numbers.FirstOrDefault(); Console.WriteLine(firstNumOrDefault); }
Result
0
This sample uses ElementAt to retrieve the second number greater than 5 from an array.
public void Linq64() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int fourthLowNum = ( from n in numbers where n > 5 select n) .ElementAt(1); // second number is index 1 because sequences use 0-based indexing Console.WriteLine("Second number > 5: {0}", fourthLowNum); }
Result
Second number > 5: 8
This sample uses orderby to sort a list of words alphabetically.
public void Linq28() { string[] words = { "cherry", "apple", "blueberry" }; var sortedWords = from w in words orderby w select w; Console.WriteLine("The sorted list of words:"); foreach (var w in sortedWords) { Console.WriteLine(w); } }
Result
The sorted list of words:
apple
blueberry
cherry
apple
blueberry
cherry
This sample uses orderby to sort a list of words by length.
public void Linq29() { string[] words = { "cherry", "apple", "blueberry" }; var sortedWords = from w in words orderby w.Length select w; Console.WriteLine("The sorted list of words (by length):"); foreach (var w in sortedWords) { Console.WriteLine(w); } }
Result
The sorted list of words (by length):
apple
cherry
blueberry
apple
cherry
blueberry
This sample uses an OrderBy clause with a custom comparer to do a case-insensitive sort of the words in an array.
public void Linq31() { string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }; var sortedWords = words.OrderBy(a => a, new CaseInsensitiveComparer()); ObjectDumper.Write(sortedWords); } public class CaseInsensitiveComparer : IComparer<string> { public int Compare(string x, string y) { return string.Compare(x, y, StringComparison.OrdinalIgnoreCase); } }
Result
AbAcUs
aPPLE
BlUeBeRrY
bRaNcH
cHeRry
ClOvEr
aPPLE
BlUeBeRrY
bRaNcH
cHeRry
ClOvEr
This sample uses orderby and descending to sort a list of doubles from highest to lowest.
public void Linq32() { double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 }; var sortedDoubles = from d in doubles orderby d descending select d; Console.WriteLine("The doubles from highest to lowest:"); foreach (var d in sortedDoubles) { Console.WriteLine(d); } }
Result
The doubles from highest to lowest:
4.1
2.9
2.3
1.9
1.7
4.1
2.9
2.3
1.9
1.7
No comments:
Post a Comment