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. [Android开发常见问题-11] Unable to execute dex: Multiple dex files define 解决方法

    最近在开发一个工程,其中用到了一个开源的库项目Android-ViewPagerIndicator. 这个项目是作为一个库出现的,如下图: 这个项目中包含了android-support-v4.jar ...

  2. jvm回收方法区

    很多人认为方法区(或者HotSpot虚拟机中的永久代)是没有垃圾收集的,Java虚拟机规范中确实说过可以不要求虚拟机在方法区实现垃圾收集,而且在方法区进行垃圾收集的“性价比”一般比较低:在堆中,尤其是 ...

  3. LaTeX入门教程

    LaTeX(LATEX,音译"拉泰赫")是一种基于ΤΕΧ的排版系统,由美国计算机学家莱斯利·兰伯特(Leslie Lamport)在20世纪80年代初期开发,利用这种格式,即使使用 ...

  4. 【Spring】基于注解的实现SpringMVC+MySQL

    目录结构: // contents structure [-] SprinigMVC是什么 SpringMVC工作原理 @Controller和@RequestMapping注解 @Controlle ...

  5. java基础练习 4

    import java.util.Scanner; public class Forth { public static void main(String[] args){ /*请输入星期几的第一个字 ...

  6. cocos2d-x中DrawNode常见的图像绘制函数

    //绘制矩形  ('起始点' , '目标点' , '填充颜色') auto rect=DrawNode::create(); rect->drawRect(Vec2(0,0),Vec2(100, ...

  7. input失效后,怎么改变它默认就有的灰色

    ☆☆☆☆☆ input:disabled { -webkit-text-fill-color: rgba(0, 0, 0, 1); -webkit-opacity: 1; } 去掉button/sel ...

  8. Java 并发 线程同步

    Java 并发 线程同步 @author ixenos 同步 1.异步线程本身包含了执行时需要的数据和方法,不需要外部提供的资源和方法,在执行时也不关心与其并发执行的其他线程的状态和行为 2.然而,大 ...

  9. C#重写url

    string url = Request.Url.LocalPath; Context.RewritePath(url + "?id=1111&name=gdwy"); 或 ...

  10. 正则表达式之 match , findall, sub,subn

    #正则表达式之 match以及分组 import re #无分组 origin = "hello alex bcd alex lge alex avd 19" r = re.mat ...