GroupBy - Simple 2
public void Linq41()
{
string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" }; var wordGroups =
from w in words
group w by w[] 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
GroupBy - Simple 3
public void Linq42()
{
List<Product> products = GetProductList(); var orderGroups =
from p in products
group p by p.Category into g
select new { Category = g.Key, Products = g }; ObjectDumper.Write(orderGroups, );
}
Category=Beverages Products=...
Products: ProductID=1 ProductName=Chai Category=Beverages UnitPrice=18.0000 UnitsInStock=39
Products: ProductID=2 ProductName=Chang Category=Beverages UnitPrice=19.0000 UnitsInStock=17
Products: ProductID=24 ProductName=Guaraná Fantástica Category=Beverages UnitPrice=4.5000 UnitsInStock=20
Products: ProductID=34 ProductName=Sasquatch Ale Category=Beverages UnitPrice=14.0000 UnitsInStock=111
Products: ProductID=35 ProductName=Steeleye Stout Category=Beverages UnitPrice=18.0000 UnitsInStock=20
Products: ProductID=38 ProductName=Côte de Blaye Category=Beverages UnitPrice=263.5000 UnitsInStock=17
Products: ProductID=39 ProductName=Chartreuse verte Category=Beverages UnitPrice=18.0000 UnitsInStock=69
Products: ProductID=43 ProductName=Ipoh Coffee Category=Beverages UnitPrice=46.0000 UnitsInStock=17
Products: ProductID=67 ProductName=Laughing Lumberjack Lager Category=Beverages UnitPrice=14.0000 UnitsInStock=52
Products: ProductID=70 ProductName=Outback Lager Category=Beverages UnitPrice=15.0000 UnitsInStock=15
Products: ProductID=75 ProductName=Rhönbräu Klosterbier Category=Beverages UnitPrice=7.7500 UnitsInStock=125
Products: ProductID=76 ProductName=Lakkalikööri Category=Beverages UnitPrice=18.0000 UnitsInStock=57
Category=Condiments Products=...
Products: ProductID=3 ProductName=Aniseed Syrup Category=Condiments UnitPrice=10.0000 UnitsInStock=13
Products: ProductID=4 ProductName=Chef Anton's Cajun Seasoning Category=Condiments UnitPrice=22.0000 UnitsInStock=53
GroupBy - Nested
public void Linq43()
{
List<Customer> customers = GetCustomerList(); var customerOrderGroups =
from c in customers
select
new
{
c.CompanyName,
YearGroups =
from o in c.Orders
group o by o.OrderDate.Year into yg
select
new
{
Year = yg.Key,
MonthGroups =
from o in yg
group o by o.OrderDate.Month into mg
select new { Month = mg.Key, Orders = mg }
}
}; ObjectDumper.Write(customerOrderGroups, );
}
Result
CompanyName=Alfreds Futterkiste YearGroups=...
YearGroups: Year=1997 MonthGroups=...
MonthGroups: Month=8 Orders=...
Orders: OrderID=10643 OrderDate=8/25/1997 Total=814.50
MonthGroups: Month=10 Orders=...
Orders: OrderID=10692 OrderDate=10/3/1997 Total=878.00
Orders: OrderID=10702 OrderDate=10/13/1997 Total=330.00
YearGroups: Year=1998 MonthGroups=...
MonthGroups: Month=1 Orders=...
Orders: OrderID=10835 OrderDate=1/15/1998 Total=845.80
MonthGroups: Month=3 Orders=...
Orders: OrderID=10952 OrderDate=3/16/1998 Total=471.20
MonthGroups: Month=4 Orders=...
Orders: OrderID=11011 OrderDate=4/9/1998 Total=933.50
CompanyName=Ana Trujillo Emparedados y helados YearGroups=...
YearGroups: Year=1996 MonthGroups=...
MonthGroups: Month=9 Orders=...
Orders: OrderID=10308 OrderDate=9/18/1996 Total=88.80
YearGroups: Year=1997 MonthGroups=...
MonthGroups: Month=8 Orders=...
Orders: OrderID=10625 OrderDate=8/8/1997 Total=479.75
MonthGroups: Month=11 Orders=...
Orders: OrderID=10759 OrderDate=11/28/1997 Total=320.00
YearGroups: Year=1998 MonthGroups=...
MonthGroups: Month=3 Orders=...
GroupBy - Comparer
public void Linq44()
{
string[] anagrams = { "from ", " salt", " earn ", " last ", " near ", " form " }; var orderGroups = anagrams.GroupBy(w => w.Trim(), new AnagramEqualityComparer()); ObjectDumper.Write(orderGroups, );
} public class AnagramEqualityComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return getCanonicalString(x) == getCanonicalString(y);
} public int GetHashCode(string obj)
{
return getCanonicalString(obj).GetHashCode();
} private string getCanonicalString(string word)
{
char[] wordChars = word.ToCharArray();
Array.Sort<char>(wordChars);
return new string(wordChars);
}
}
Result
...
from
form
...
salt
last
...
earn
near
GroupBy - Comparer, Mapped
public void Linq45()
{
string[] anagrams = { "from ", " salt", " earn ", " last ", " near ", " form " }; var orderGroups = anagrams.GroupBy(
w => w.Trim(),
a => a.ToUpper(),
new AnagramEqualityComparer()
); ObjectDumper.Write(orderGroups, );
} public class AnagramEqualityComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return getCanonicalString(x) == getCanonicalString(y);
} public int GetHashCode(string obj)
{
return getCanonicalString(obj).GetHashCode();
} private string getCanonicalString(string word)
{
char[] wordChars = word.ToCharArray();
Array.Sort<char>(wordChars);
return new string(wordChars);
}
}
...
FROM
FORM
...
SALT
LAST
...
EARN
NEAR
Distinct - 1
public void Linq46()
{
int[] factorsOf300 = { , , , , }; var uniqueFactors = factorsOf300.Distinct(); Console.WriteLine("Prime factors of 300:");
foreach (var f in uniqueFactors)
{
Console.WriteLine(f);
}
}
Prime factors of 300:
2
3
5
Distinct - 2
public void Linq47()
{
List<Product> products = GetProductList(); var categoryNames = (
from p in products
select p.Category)
.Distinct(); Console.WriteLine("Category names:");
foreach (var n in categoryNames)
{
Console.WriteLine(n);
}
}
Category names:
Beverages
Condiments
Produce
Meat/Poultry
Seafood
Dairy Products
Confections
Grains/Cereals
Union - 1
public void Linq48()
{
int[] numbersA = { , , , , , , };
int[] numbersB = { , , , , }; var uniqueNumbers = numbersA.Union(numbersB); Console.WriteLine("Unique numbers from both arrays:");
foreach (var n in uniqueNumbers)
{
Console.WriteLine(n);
}
}
Unique numbers from both arrays:
0
2
4
5
6
8
9
1
3
7
Union - 2
public void Linq49()
{
List<Product> products = GetProductList();
List<Customer> customers = GetCustomerList(); var productFirstChars =
from p in products
select p.ProductName[];
var customerFirstChars =
from c in customers
select c.CompanyName[]; var uniqueFirstChars = productFirstChars.Union(customerFirstChars); Console.WriteLine("Unique first letters from Product names and Customer names:");
foreach (var ch in uniqueFirstChars)
{
Console.WriteLine(ch);
}
}
Result
Unique first letters from Product names and Customer names:
C
A
G
U
N
M
I
Q
K
T
P
S
R
B
J
Z
V
F
E
W
L
O
D
H
Intersect - 1
public void Linq50()
{
int[] numbersA = { , , , , , , };
int[] numbersB = { , , , , }; var commonNumbers = numbersA.Intersect(numbersB); Console.WriteLine("Common numbers shared by both arrays:");
foreach (var n in commonNumbers)
{
Console.WriteLine(n);
}
}
Common numbers shared by both arrays:
5
8
Intersect - 2
public void Linq51()
{
List<Product> products = GetProductList();
List<Customer> customers = GetCustomerList(); var productFirstChars =
from p in products
select p.ProductName[];
var customerFirstChars =
from c in customers
select c.CompanyName[]; var commonFirstChars = productFirstChars.Intersect(customerFirstChars); Console.WriteLine("Common first letters from Product names and Customer names:");
foreach (var ch in commonFirstChars)
{
Console.WriteLine(ch);
}
}
Common first letters from Product names and Customer names:
C
A
G
N
M
I
Q
K
T
P
S
R
B
V
F
E
W
L
O
Except - 1
public void Linq52()
{
int[] numbersA = { , , , , , , };
int[] numbersB = { , , , , }; IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB); Console.WriteLine("Numbers in first array but not second array:");
foreach (var n in aOnlyNumbers)
{
Console.WriteLine(n);
}
}
Numbers in first array but not second array:
0
2
4
6
9
Except - 2
public void Linq53()
{
List<Product> products = GetProductList();
List<Customer> customers = GetCustomerList(); var productFirstChars =
from p in products
select p.ProductName[];
var customerFirstChars =
from c in customers
select c.CompanyName[]; var productOnlyFirstChars = productFirstChars.Except(customerFirstChars); Console.WriteLine("First letters from Product names, but not from Customer names:");
foreach (var ch in productOnlyFirstChars)
{
Console.WriteLine(ch);
}
}
First letters from Product names, but not from Customer names:
U
J
Z
ToArray
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 = ; d < doublesArray.Length; d += )
{
Console.WriteLine(doublesArray[d]);
}
}
Result
Every other double from highest to lowest:
4.1
2.3
1.7
ToList
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
ToDictionary
public void Linq56()
{
var scoreRecords = new[] { new {Name = "Alice", Score = },
new {Name = "Bob" , Score = },
new {Name = "Cathy", Score = }
}; var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name); Console.WriteLine("Bob's score: {0}", scoreRecordsDict["Bob"]);
}
Bob's score: { Name = Bob, Score = 40 }
OfType
public void Linq57()
{
object[] numbers = { null, 1.0, "two", , "four", , "six", 7.0 }; var doubles = numbers.OfType<double>(); Console.WriteLine("Numbers stored as doubles:");
foreach (var d in doubles)
{
Console.WriteLine(d);
}
}
Numbers stored as doubles:
1
7
First - Simple
public void Linq58()
{
List<Product> products = GetProductList(); Product product12 = (
from p in products
where p.ProductID ==
select p)
.First(); ObjectDumper.Write(product12);
}
Result
ProductID=12 ProductName=Queso Manchego La Pastora Category=Dairy Products UnitPrice=38.0000 UnitsInStock=86
First - Condition
public void Linq59()
{
string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; string startsWithO = strings.First(s => s[] == 'o'); Console.WriteLine("A string starting with 'o': {0}", startsWithO);
}
Result
A string starting with 'o': one
FirstOrDefault - Simple
public void Linq61() {
int[] numbers = { }; int firstNumOrDefault = numbers.FirstOrDefault(); Console.WriteLine(firstNumOrDefault);
}
Result
0