2009-02-11

Linq 基本語法-Select

在看Apress.Pro LINQ(作者Joseph C. Rattz,Jr.)這本書時
看到這段範例(稍微改寫過)
Example1
首先定義一個字串陣列presidents

string[] presidents = {"Adams", "Arthur", "Buchanan", "Bush", "Carter", "Cleveland",    
"Clinton", "Coolidge", "Eisenhower", "Fillmore", "Ford", "Garfield",    
"Grant", "Harding", "Harrison", "Hayes", "Hoover", "Jackson",    
"Jefferson", "Johnson", "Kennedy", "Lincoln", "Madison", "McKinley",    
"Monroe", "Nixon", "Pierce", "Polk", "Reagan", "Roosevelt", "Taft",    
"Taylor", "Truman", "Tyler", "Van Buren", "Washington", "Wilson"};

Select語法:
var nameObjs = presidents.Select((p,i) => new { Index=i, Name=p });
StringBuilder sb = new StringBuilder();
 
foreach (var item in nameObjs)
{
  string name = string.Format(@"{0}. {1}",item.Index+1,item.Name);
  sb.AppendLine(name);
}
 
richTextBox1.Text = sb.ToString();

最後產生的結果如下
image

Example2(SelectMany用法)

Employee[] employees = Employee.GetEmployeesArray();
EmployeeOptionEntry[] empOptions = EmployeeOptionEntry.GetEmployeeOptionEntries();
 
var employeeOptions = employees
.SelectMany(e => empOptions
.Where(eo => eo.id == e.id)
.Select(eo => new {
id = eo.id,
optionsCount = eo.optionsCount }));
 
foreach (var item in employeeOptions)
  Console.WriteLine(item);


其實看完這個範例,我還是依舊不懂
所以上網查了一下,看到這兩篇文章
http://www.tzwhx.com/newOperate/html/1/11/112/14415.html
http://www.cnblogs.com/aspnet2008/archive/2008/12/19/1357690.html
大概看了一下,好像是因為Linq語法並沒有SQL的Join
才會有SelectMany這個方法,我不確定先記錄下來!

沒有留言:

張貼留言