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. NodeJS系列-部署

    NodeJS系列-部署 NodeJS我就不介绍了,被标题吸引进来的人可以看这个链接,了解NodeJS.下来就开始关于NodeJS开发的指南. NodeJS可以部署的平台有Windows,Unix,iO ...

  2. 提高Java代码质量的Eclipse插件之Checkstyle的使用详解

    提高Java代码质量的Eclipse插件之Checkstyle的使用详解 CheckStyle是SourceForge下的一个项目,提供了一个帮助JAVA开发人员遵守某些编码规范的工具.它能够自动化代 ...

  3. 原生javascript-图片按钮切换

    原生javascript-图片按钮切换 即上次被分配写原生JS相册弹窗后,这次又接到了写原生JS,图片按钮切换,真激情: 个人在线实例:http://www.lgyweb.com/picSwitch/ ...

  4. 通用高性能 Windows Socket 组件 HP-Socket v2.2.2 更新发布

    HP-Socket 是一套通用的高性能 Windows Socket 组件包,包含服务端组件(IOCP 模型)和客户端组件(Event Select 模型),广泛适用于 Windows 平台的 TCP ...

  5. Qt Creator+MinGW+boost特殊函数的使用示例

    Qt Creator+MinGW+boost特殊函数的使用示例: 先编译和安装boost: bootstrap.bat gcc .\b2 --toolset=gcc --prefix=E:\boost ...

  6. HashMap完全解读

    一.什么是HashMap 基于哈希表的 Map 接口的实现.此实现提供所有可选的映射操作,并允许使用 null 值和 null 键.(除了非同步和允许使用 null 之外,HashMap 类与 Has ...

  7. ASP.NET网站运行常见错误以及解决方法(持续更新)

    一.A potentially dangerous Request.Form value was detected from the client 用户在页面上提交表单到服务器时,服务器会检测到一些潜 ...

  8. NSClassFromString,NSSelectorFromString,isKingOfClass

    1. NSClassFromString 这个方法判断类是否存在,如果存在就动态加载的,不存为就返回一个空对象; id myObj = [[NSClassFromString(@"MySpe ...

  9. make -j 多核并行编译 导致笔记本过热 自动关机保护

    中午在装着CentOS的笔记本上把 Oneinstack 跑起来然后去上班了,本来等着下班回来用的,回来之后发现是关机状态,环境也没有装好. 查看日志,找不到相关信息,甚至还以为是被入侵了.又试了几遍 ...

  10. RelativeLayout各个属性

    android:layout_above="@id/xxx"  --将控件置于给定ID控件之上 android:layout_below="@id/xxx"  ...