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. cooking eggs

    1: what is egg? what's the shape of it in details? 2: can egg run like this http://item.taobao.com/i ...

  2. Kendo UI开发教程(6): Kendo DataSource 概述

    Kendo 的数据源支持本地数据源(JavaScript 对象数组),或者远程数据源(XML, JSON, JSONP),支持CRUD操作(创建,读取,更新和删除操作),并支持排序,分页,过滤,分组和 ...

  3. andoid x项目的优化 1

    通常我们写程序,都是在项目计划的压力下完成的,此时完成的代码可以完成具体业务逻辑,但是性能不一定是最优化的,一般来说,一般来说,优秀的程序员在写完代码之后都会不断的对代码进行重构.重构的好处有很多,其 ...

  4. 如何Windows系统中搭建php环境

    PHP介绍: PHP 独特的语法混合了C.Java.Perl以及PHP自创的语法.它可以比CGI或者Perl更快速地执行动态网页.用PHP做出的动态页面与其他的编程语言相比,PHP是将程序嵌入到HTM ...

  5. 【实用技巧】去除BootStrap所有圆角效果

    满屏的圆角有没有审"美"疲劳啊?教你一键去除所有圆角效果: * { -webkit-border-radius: 0 !important; -moz-border-radius: ...

  6. [转载]关于shell脚本的基本语法

    关于shell脚本的基本语法 整理于:2014-03-31,何俭飞,mymladdr@sina.com 一.执行 1.shell脚本如果要被执行,一般地必须要有执行权限"x"(除了 ...

  7. (转载)python日期函数

    转载于http://www.cnblogs.com/emanlee/p/4399147.html 所有日期.时间的api都在datetime模块内. 1. 日期输出格式化 datetime => ...

  8. configure HDFS(hadoop 分布式文件系统) high available

    注:来自尚学堂小陈老师上课笔记 1.安装启动zookeeper a)上传解压zookeeper包 b)cp zoo_sample.cfg zoo.cfg修改zoo.cfg文件 c)dataDir=/o ...

  9. linux的环境变量设置

    source/etc/profile是让/etc/profile文件修改后立即生效, 还有一种方法是:. /etc/profile 注意:.和/etc/profile有空格 linux中source命 ...

  10. 使用pycharm+pyqt5 调取界面程序

    一.使用QtDesigner制作界面 1)打开的界面设计工具QtDesigner,如图: 2)新建窗体,选择Main Window: 3)分别在窗口添加如下控件,Calendar.3个pushButt ...