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, );
}
 Result

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);
}
}
 Result

...
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);
}
}
Result

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);
}
}
 Result

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);
}
}
Result

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);
}
}
 Result

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);
}
}
Result

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);
}
}
 Result

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);
}
}
Result

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"]);
}
Result

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);
}
}
Result

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

101个Linq例子(40-60)的更多相关文章

  1. 101个linq例子

    FirstOrDefault - Simple public void Linq61() { int[] numbers = { }; int firstNumOrDefault = numbers. ...

  2. 101个Linq的例子

    Where - Simple 1 筛选出数值中大于5的元素 public void Linq1() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 } ...

  3. 101个LINQ示例,包含几乎全部操作

    Restriction Operators Where - Simple public void Linq1() { , , , , , , , , , }; var lowNums = from n ...

  4. Hdu2102 A计划 2017-01-18 14:40 60人阅读 评论(0) 收藏

    A计划 Time Limit : 3000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other) Total Submissio ...

  5. asp.net、mvc、ajax、js、jquery、sql、EF、linq、netadvantage第三方控件知识点笔记

    很简单,如下: 父页面:(弹出提示框) function newwindow(obj) { var rtn = window.showModalDialog('NewPage.htm','','sta ...

  6. Linq和Lamda表达式的简单处理方式

    一 什么是LINQ? LINQ即Language Integrated Query(语言集成查询),LINQ是集成到C#和Visual Basic.NET这些语言中用于提供查询数据能力的一个新特性. ...

  7. LINQ Enumerable 续 II

    Enumerable.TakeWhile和Enumerable.SkpWhile Enumerable.TakeWhile和Enumerable.SkpWhile将通过判断条件,来获取和跳过序列. T ...

  8. linq 为什么要用linq linq写法

    LINQ,语言集成查询(Language Integrated Query)是一组用于c#和Visual Basic语言的扩展.它允许编写C#或者Visual Basic代码以查询数据库相同的方式操作 ...

  9. nodejs中使用linq

    官网地址 https://github.com/mihaifm/linq 安装 npm install linq 导入 var Enumerable = require(‘linq‘); 例子 1 总 ...

随机推荐

  1. oracle中backup模式

    在数据库打开的情况下备份(归档模式),把表空间或者数据库置于backup 模式下, 如: SQL> alter database  begin  backup; Database altered ...

  2. mmap学习

    mmap学习 内存页: Linux是以页为单位来管理物理内存的,一页大小一般等于4096字节.页容量越大,系统中可能存在的内存碎片就越多. mmap将一个磁盘上的文件或者对象映射进内存.文件被映射到多 ...

  3. 搭建WEB邮件系统,爆强!

    Linux+postfix+extmail+dovecot打造基于web页面的邮件系统 原文地址: http://blog.csdn.net/deansrk/article/details/67177 ...

  4. Mysql监控及优化

    一.Mysql连接数 1.配置Mysql连接数: vim /etc/my.cnf [mysqld]下面修改 max_connections=1000 不写默认为100. wait_timeout=60 ...

  5. SSH三大框架的基本整合以及常见错误的解决方法

    一.新建项目 eclipse->file->new->other->Dynamic Web Project,project name为sshDemo 二.下载jar包 1.st ...

  6. C#中的集合类——HashTable

    HashTable 被称为键值对集合,类似于字典,根据key可以找到value 键值对对象[键]=值;键值对集合当中,键必须是唯一的,而值是可以重复的 1. HashTable的用法 //创建了一个键 ...

  7. vue-auto-focus: 控制自动聚焦行为的 vue 指令

    在网页的表单中,经常需要用程序来控制input和textarea的自动聚焦行为.例如我最近做的一个项目,有个装箱出库的流程,input框自动聚焦的流程如下:页面进入时自动聚焦到订单号输入框->订 ...

  8. js实现表格的增删改查

    这份代码实现了对表格的增加,删除,更改,查询. 点击一次添加按钮,表格会增加一行. 点击重置按钮,输入框的内容会被清空. 添加一行后,最后两格为更改和删除.点击更改,原有内容会各自显示在一个输入框内, ...

  9. 《Dynamic Topic Detection and Tracking: A Comparison of HDP, C-Word, and Cocitation Methods》笔记

    原文地址:http://onlinelibrary.wiley.com/doi/10.1002/asi.23134/abstract 黄色背景是我认为比较重要的,红色字体是我自己的话. 动态主题监测与 ...

  10. WebTours服务的启动

    简介: HP loadrunner自带的一个飞机系统订票网站. 启动服务的步骤: 1.启动StartServer.bat 所在的路径: (\HP LoadRunner 12.02 Community ...