-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
GroupBy-Sample-2.cs
65 lines (60 loc) · 2.07 KB
/
GroupBy-Sample-2.cs
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System.Linq;
using System;
namespace Grouping
{
public class GroupBy2
{
//This sample uses group by to partition a list of words by their first letter.
//Outputs the following to the console:
// 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
public static void QuerySyntaxExample()
{
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);
}
}
}
//This sample uses group by to partition a list of words by their first letter.
//Outputs the following to the console:
// 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
public static void MethodSyntaxExample()
{
string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" };
var wordGroups = words.GroupBy(w => w[0],
(Key, g) => new { FirstLetter = 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);
}
}
}
}
}