您的位置:首页 > 其它

101个Linq的例子

2015-07-16 23:30 239 查看

Where-Simple1

筛选出数值中大于5的元素

publicvoidLinq1()
{
int[]numbers={5,4,1,3,9,8,6,7,2,0};

varlowNums=
fromninnumbers
wheren<5
selectn;

Console.WriteLine("Numbers<5:");
foreach(varxinlowNums)
{
Console.WriteLine(x);
}
}


Result

Numbers<5:
4
1
3
2
0


Where-Simple2

筛选出所有没有现货的产品

publicvoidLinq2()
{
List<Product>products=GetProductList();

varsoldOutProducts=
frompinproducts
wherep.UnitsInStock==0
selectp;

Console.WriteLine("Soldoutproducts:");
foreach(varproductinsoldOutProducts)
{
Console.WriteLine("{0}issoldout!",product.ProductName);
}
}


Result

Soldoutproducts:
ChefAnton'sGumboMixissoldout!
AliceMuttonissoldout!
ThüringerRostbratwurstissoldout!
GorgonzolaTelinoissoldout!
PerthPastiesissoldout!


Where-Simple3

筛选充所有产品中有现货并且价格大于3的产品

publicvoidLinq3()
{
List<Product>products=GetProductList();

varexpensiveInStockProducts=
frompinproducts
wherep.UnitsInStock>0&&p.UnitPrice>3.00M
selectp;

Console.WriteLine("In-stockproductsthatcostmorethan3.00:");
foreach(varproductinexpensiveInStockProducts)
{
Console.WriteLine("{0}isinstockandcostsmorethan3.00.",product.ProductName);
}
}


Result

In-stockproductsthatcostmorethan3.00:
Chaiisinstockandcostsmorethan3.00.
Changisinstockandcostsmorethan3.00.
AniseedSyrupisinstockandcostsmorethan3.00.
ChefAnton'sCajunSeasoningisinstockandcostsmorethan3.00.
Grandma'sBoysenberrySpreadisinstockandcostsmorethan3.00.
UncleBob'sOrganicDriedPearsisinstockandcostsmorethan3.00.
NorthwoodsCranberrySauceisinstockandcostsmorethan3.00.
MishiKobeNikuisinstockandcostsmorethan3.00.
Ikuraisinstockandcostsmorethan3.00.
QuesoCabralesisinstockandcostsmorethan3.00.
QuesoManchegoLaPastoraisinstockandcostsmorethan3.00.
Konbuisinstockandcostsmorethan3.00.
Tofuisinstockandcostsmorethan3.00.


Where-Drilldown

筛选中在华盛顿的所有客户,显示出他们的订单单号和订单日期

publicvoidLinq4()
{
List<Customer>customers=GetCustomerList();

varwaCustomers=
fromcincustomers
wherec.Region=="WA"
selectc;

Console.WriteLine("CustomersfromWashingtonandtheirorders:");
foreach(varcustomerinwaCustomers)
{
Console.WriteLine("Customer{0}:{1}",customer.CustomerID,customer.CompanyName);
foreach(varorderincustomer.Orders)
{
Console.WriteLine("Order{0}:{1}",order.OrderID,order.OrderDate);
}
}
}


Result

CustomersfromWashingtonandtheirorders:
CustomerLAZYK:LazyKKountryStore

Order10482:3/21/199712:00:00AM

Order10545:5/22/199712:00:00AM
CustomerTRAIH:Trail'sHeadGourmetProvisioners

Order10574:6/19/199712:00:00AM

Order10577:6/23/199712:00:00AM

Order10822:1/8/199812:00:00AM
CustomerWHITC:WhiteCloverMarkets

Order10269:7/31/199612:00:00AM

Order10344:11/1/199612:00:00AM

Order10469:3/10/199712:00:00AM

Order10483:3/24/199712:00:00AM


Where-Indexed

筛选出字符串长度小于自己索引的元素

publicvoidLinq5()
{
string[]digits={"zero","one","two","three","four","five","six","seven","eight","nine"};

varshortDigits=digits.Where((digit,index)=>digit.Length<index);

Console.WriteLine("Shortdigits:");
foreach(vardinshortDigits)
{
Console.WriteLine("Theword{0}isshorterthanitsvalue.",d);
}
}


Result

Shortdigits:
Thewordfiveisshorterthanitsvalue.
Thewordsixisshorterthanitsvalue.
Thewordsevenisshorterthanitsvalue.
Thewordeightisshorterthanitsvalue.
Thewordnineisshorterthanitsvalue.




Select-Simple1

publicvoidLinq6()
{
int[]numbers={5,4,1,3,9,8,6,7,2,0};

varnumsPlusOne=
fromninnumbers
selectn+1;

Console.WriteLine("Numbers+1:");
foreach(variinnumsPlusOne)
{
Console.WriteLine(i);
}
}


Result

Numbers+1:
6
5
2
4
10
9
7
8
3
1

Select-Simple2

publicvoidLinq7()
{
List<Product>products=GetProductList();

varproductNames=
frompinproducts
selectp.ProductName;

Console.WriteLine("ProductNames:");
foreach(varproductNameinproductNames)
{
Console.WriteLine(productName);
}
}


Result

ProductNames:
Chai
Chang
AniseedSyrup
ChefAnton'sCajunSeasoning
ChefAnton'sGumboMix
Grandma'sBoysenberrySpread
UncleBob'sOrganicDriedPears
NorthwoodsCranberrySauce
MishiKobeNiku
Ikura
QuesoCabrales
QuesoManchegoLaPastora
Konbu
Tofu
GenenShouyu
Pavlova
AliceMutton
CarnarvonTigers
TeatimeChocolateBiscuits
SirRodney'sMarmalade

Select-Transformation

publicvoidLinq8()
{
int[]numbers={5,4,1,3,9,8,6,7,2,0};
string[]strings={"zero","one","two","three","four","five","six","seven","eight","nine"};

vartextNums=
fromninnumbers
selectstrings
;

Console.WriteLine("Numberstrings:");
foreach(varsintextNums)
{
Console.WriteLine(s);
}
}


Result

Numberstrings:
five
four
one
three
nine
eight
six
seven
two
zero

Select-AnonymousTypes1

publicvoidLinq9()
{
string[]words={"aPPLE","BlUeBeRrY","cHeRry"};

varupperLowerWords=
fromwinwords
selectnew{Upper=w.ToUpper(),Lower=w.ToLower()};

foreach(varulinupperLowerWords)
{
Console.WriteLine("Uppercase:{0},Lowercase:{1}",ul.Upper,ul.Lower);
}
}


Result

Uppercase:APPLE,Lowercase:apple
Uppercase:BLUEBERRY,Lowercase:blueberry
Uppercase:CHERRY,Lowercase:cherry

Select-AnonymousTypes2

publicvoidLinq10()
{
int[]numbers={5,4,1,3,9,8,6,7,2,0};
string[]strings={"zero","one","two","three","four","five","six","seven","eight","nine"};

vardigitOddEvens=
fromninnumbers
selectnew{Digit=strings
,Even=(n%2==0)};

foreach(vardindigitOddEvens)
{
Console.WriteLine("Thedigit{0}is{1}.",d.Digit,d.Even?"even":"odd");
}
}


Result

Thedigitfiveisodd.
Thedigitfouriseven.
Thedigitoneisodd.
Thedigitthreeisodd.
Thedigitnineisodd.
Thedigiteightiseven.
Thedigitsixiseven.
Thedigitsevenisodd.
Thedigittwoiseven.
Thedigitzeroiseven.

Select-AnonymousTypes3

publicvoidLinq11()
{
List<Product>products=GetProductList();

varproductInfos=
frompinproducts
selectnew{p.ProductName,p.Category,Price=p.UnitPrice};

Console.WriteLine("ProductInfo:");
foreach(varproductInfoinproductInfos)
{
Console.WriteLine("{0}isinthecategory{1}andcosts{2}perunit.",productInfo.ProductName,productInfo.Category,productInfo.Price);
}
}


Result

ProductInfo:
ChaiisinthecategoryBeveragesandcosts18.0000perunit.
ChangisinthecategoryBeveragesandcosts19.0000perunit.
AniseedSyrupisinthecategoryCondimentsandcosts10.0000perunit.
ChefAnton'sCajunSeasoningisinthecategoryCondimentsandcosts22.0000perunit.
ChefAnton'sGumboMixisinthecategoryCondimentsandcosts21.3500perunit.
Grandma'sBoysenberrySpreadisinthecategoryCondimentsandcosts25.0000perunit.
UncleBob'sOrganicDriedPearsisinthecategoryProduceandcosts30.0000perunit.
NorthwoodsCranberrySauceisinthecategoryCondimentsandcosts40.0000perunit.
MishiKobeNikuisinthecategoryMeat/Poultryandcosts97.0000perunit.
IkuraisinthecategorySeafoodandcosts31.0000perunit.
QuesoCabralesisinthecategoryDairyProductsandcosts21.0000perunit.
QuesoManchegoLaPastoraisinthecategoryDairyProductsandcosts38.0000perunit.
KonbuisinthecategorySeafoodandcosts6.0000perunit.
TofuisinthecategoryProduceandcosts23.2500perunit.

Select-Indexed

publicvoidLinq12()
{
int[]numbers={5,4,1,3,9,8,6,7,2,0};

varnumsInPlace=numbers.Select((num,index)=>new{Num=num,InPlace=(num==index)});

Console.WriteLine("Number:In-place?");
foreach(varninnumsInPlace)
{
Console.WriteLine("{0}:{1}",n.Num,n.InPlace);
}
}


Result

Number:In-place?
5:False
4:False
1:False
3:True
9:False
8:False
6:True
7:True
2:False
0:False

Select-Filtered

publicvoidLinq13()
{
int[]numbers={5,4,1,3,9,8,6,7,2,0};
string[]digits={"zero","one","two","three","four","five","six","seven","eight","nine"};

varlowNums=
fromninnumbers
wheren<5
selectdigits
;

Console.WriteLine("Numbers<5:");
foreach(varnuminlowNums)
{
Console.WriteLine(num);
}
}


Result

Numbers<5:
four
one
three
two
zero

SelectMany-Compoundfrom1

publicvoidLinq14()
{
int[]numbersA={0,2,4,5,6,8,9};
int[]numbersB={1,3,5,7,8};

varpairs=
fromainnumbersA
frombinnumbersB
wherea<b
selectnew{a,b};

Console.WriteLine("Pairswherea<b:");
foreach(varpairinpairs)
{
Console.WriteLine("{0}islessthan{1}",pair.a,pair.b);
}
}


Result

Pairswherea<b:
0islessthan1
0islessthan3
0islessthan5
0islessthan7
0islessthan8
2islessthan3
2islessthan5
2islessthan7
2islessthan8
4islessthan5
4islessthan7
4islessthan8
5islessthan7
5islessthan8
6islessthan7
6islessthan8

SelectMany-Compoundfrom2

publicvoidLinq15()
{
List<Customer>customers=GetCustomerList();

varorders=
fromcincustomers
fromoinc.Orders
whereo.Total<500.00M
selectnew{c.CustomerID,o.OrderID,o.Total};

ObjectDumper.Write(orders);
}


Result

CustomerID=ALFKIOrderID=10702Total=330.00
CustomerID=ALFKIOrderID=10952Total=471.20
CustomerID=ANATROrderID=10308Total=88.80
CustomerID=ANATROrderID=10625Total=479.75
CustomerID=ANATROrderID=10759Total=320.00
CustomerID=ANTONOrderID=10365Total=403.20
CustomerID=ANTONOrderID=10682Total=375.50
CustomerID=AROUTOrderID=10355Total=480.00

SelectMany-Compoundfrom3

publicvoidLinq16()
{
List<Customer>customers=GetCustomerList();

varorders=
fromcincustomers
fromoinc.Orders
whereo.OrderDate>=newDateTime(1998,1,1)
selectnew{c.CustomerID,o.OrderID,o.OrderDate};

ObjectDumper.Write(orders);
}


Result

CustomerID=ALFKIOrderID=10835OrderDate=1/15/1998
CustomerID=ALFKIOrderID=10952OrderDate=3/16/1998
CustomerID=ALFKIOrderID=11011OrderDate=4/9/1998
CustomerID=ANATROrderID=10926OrderDate=3/4/1998
CustomerID=ANTONOrderID=10856OrderDate=1/28/1998
CustomerID=AROUTOrderID=10864OrderDate=2/2/1998
CustomerID=AROUTOrderID=10920OrderDate=3/3/1998
CustomerID=AROUTOrderID=10953OrderDate=3/16/1998
CustomerID=AROUTOrderID=11016OrderDate=4/10/1998
CustomerID=BERGSOrderID=10837OrderDate=1/16/1998

SelectMany-fromAssignment

publicvoidLinq17()
{
List<Customer>customers=GetCustomerList();

varorders=
fromcincustomers
fromoinc.Orders
whereo.Total>=2000.0M
selectnew{c.CustomerID,o.OrderID,o.Total};

ObjectDumper.Write(orders);
}


Result

CustomerID=ANTONOrderID=10573Total=2082.00
CustomerID=AROUTOrderID=10558Total=2142.90
CustomerID=AROUTOrderID=10953Total=4441.25
CustomerID=BERGSOrderID=10384Total=2222.40
CustomerID=BERGSOrderID=10524Total=3192.65
CustomerID=BERGSOrderID=10672Total=3815.25
CustomerID=BERGSOrderID=10857Total=2048.21
CustomerID=BLONPOrderID=10360Total=7390.20
CustomerID=BOLIDOrderID=10801Total=3026.85
CustomerID=BONAPOrderID=10340Total=2436.18
CustomerID=BONAPOrderID=10511Total=2550.00
CustomerID=BOTTMOrderID=10742Total=3118.00
CustomerID=BOTTMOrderID=10949Total=4422.00
CustomerID=CHOPSOrderID=10519Total=2314.20
CustomerID=CHOPSOrderID=10746Total=2311.70
CustomerID=COMMIOrderID=10290Total=2169.00

SelectMany-Multiplefrom

publicvoidLinq18()
{
List<Customer>customers=GetCustomerList();

DateTimecutoffDate=newDateTime(1997,1,1);

varorders=
fromcincustomers
wherec.Region=="WA"
fromoinc.Orders
whereo.OrderDate>=cutoffDate
selectnew{c.CustomerID,o.OrderID};

ObjectDumper.Write(orders);
}


Result

CustomerID=LAZYKOrderID=10482
CustomerID=LAZYKOrderID=10545
CustomerID=TRAIHOrderID=10574
CustomerID=TRAIHOrderID=10577
CustomerID=TRAIHOrderID=10822
CustomerID=WHITCOrderID=10469
CustomerID=WHITCOrderID=10483
CustomerID=WHITCOrderID=10504
CustomerID=WHITCOrderID=10596
CustomerID=WHITCOrderID=10693
CustomerID=WHITCOrderID=10696
CustomerID=WHITCOrderID=10723
CustomerID=WHITCOrderID=10740

SelectMany-Indexed

publicvoidLinq19()
{
List<Customer>customers=GetCustomerList();

varcustomerOrders=
customers.SelectMany(
(cust,custIndex)=>
cust.Orders.Select(o=>"Customer#"+(custIndex+1)+
"hasanorderwithOrderID"+o.OrderID));

ObjectDumper.Write(customerOrders);
}


Result

Customer#1hasanorderwithOrderID10643
Customer#1hasanorderwithOrderID10692
Customer#1hasanorderwithOrderID10702
Customer#1hasanorderwithOrderID10835
Customer#1hasanorderwithOrderID10952
Customer#1hasanorderwithOrderID11011
Customer#2hasanorderwithOrderID10308
Customer#2hasanorderwithOrderID10625
Customer#2hasanorderwithOrderID10759
Customer#2hasanorderwithOrderID10926

...
Customer#90hasanorderwithOrderID10248
Customer#90hasanorderwithOrderID10615
Customer#90hasanorderwithOrderID10673
Customer#90hasanorderwithOrderID10695
Customer#90hasanorderwithOrderID10873
Customer#90hasanorderwithOrderID10879
Customer#90hasanorderwithOrderID10910
Customer#90hasanorderwithOrderID11005
Customer#91hasanorderwithOrderID10374
Customer#91hasanorderwithOrderID10611
Customer#91hasanorderwithOrderID10792
Customer#91hasanorderwithOrderID10870
Customer#91hasanorderwithOrderID10906
Customer#91hasanorderwithOrderID10998
Customer#91hasanorderwithOrderID11044
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: