LINQ相關的集合操作

2021-07-25 04:35:46 字數 2977 閱讀 5407

摘選自c#高階程式設計(第9版) --c# 5.0 & .net 4.5.1

code:

static void main(string args)

;var q = data.oftype();//oftype使用

//多個from,實際是轉為selectmany()擴充套件方法

var ferraidrivers = from r in formula1.getchampions()

from c in r.cars

where c == "ferrari"

orderby r.lastname

select r.firstname + " " + r.lastname;

//對應擴充套件方法為

var ferraidrivers2 = formula1.getchampions()

.selectmany(r => r.cars, (r, c) => new )

.where(r => r.car == "ferrari")

.orderby(r => r.racer.lastname).select(r => r.racer.firstname + " " + r.racer.lastname);

foreach (var s in ferraidrivers)

console.writeline(s);

//join

var racersandteams = (from r in

from r1 in formula1.getchampions()

from yr in r1.years

select new

join t in

from t1 in formula1.getcontructorchampions()

from yt in t1.years

select new

on r.year equals t.year

orderby t.year

select new

).take(10);

foreach (var item in racersandteams)

: ", item.year, item.racer, item.team);

}//intersect操作

func> racersbycar =

car => from r in formula1.getchampions()

from c in r.cars

where c == car

orderby r.lastname

select r;

console.writeline("world champion with ferrari and mclaren");

foreach (var racer in racersbycar("ferrari").intersect(racersbycar("mclaren")))

//zip(合併)

console.writeline("zip:");

var racernames = from r in formula1.getchampions()

where r.country == "itally"

orderby r.wins descending

select new

;var racernamesandstarts = from r in formula1.getchampions()

where r.country == "itally"

orderby r.wins descending

select new

;var racers = racernames.zip(racernamesandstarts, (a, b) => a.name + ",starts:" + b.starts);

foreach (var r in racers)

console.writeline(r);

//count sum

var query = from r in formula1.getchampions()

let nyears = r.years.count()

where nyears >= 3

orderby nyears descending, r.lastname

select new

;foreach (var r in query)

console.writeline(" ", r.name, r.timeschampion);

var countries = (from c in

from r in formula1.getchampions()

group r by r.country into c

select new

orderby c.wins descending, c.country

select c).take(5);

foreach (var c in countries)

console.writeline(" ", c.country, c.wins);

//非型別化的集合操作

var l = new arraylist(formula1.getchampions() as icollection);

var query1 = from r in l.cast()

where r.country == "usa"

orderby r.wins descending

select r;

foreach (var r in query1)

console.writeline("", r);

console.readkey();

}

private static void linqquery()

", r);

}}

注: 相關實體類見書

集合的相關操作

include using namespace std typedef struct nodenode,linklist define size sizeof node define false 0 define true 1 初始化集合 void initlinklist linklist hea...

Linq操作非泛型集合

我們都知道,linq能查詢泛型集合,確切的說是 linq能實現查詢泛型物件或者實現了ienumerable。但是,很遺憾的是諸如arraylist這樣的非泛型集合並沒有實現ienumerable。那咋辦呢?總不能把這麼絢麗的linq技術對非泛型關上大門把!其實,方法還是有的。場景還原 定義乙個car...

集合的相關操作記錄

1.給string陣列新增值的方法 list data new arraylist string value value data.add value string tostrarr list.toarray new string data.size 轉成陣列 因為字串陣列不能單獨新增值,所以可以先...