2009-02-18

Linq 基本語法 - Join

Join
The Join operator performs an inner equijoin on two sequences based on keys extracted from each element in the sequences.

public static IEnumerable<V> Join<T, U, K, V>(
this IEnumerable<T> outer,
IEnumerable<U> inner,
Func<T, K> outerKeySelector,
Func<U, K> innerKeySelector,
Func<T, U, V> resultSelector);


在這裡建立了兩個List
List ltUser = new List(20);
for (int i = 0; i < 20; i++)
{
  ltUser.Add(new User(i,"AA"));                
}
 
List ltUserInfo = new List(10);
for (int i = 0; i < 10; i++)
{
  ltUserInfo.Add(new UserInfo(i,"CC"));                
}

Linq語法如下:
var Users=ltUser.Join(ltUserInfo,
  a=>a.No,
  b=>b.No,
  (a,b)=>new{id=a.No,UserName=a.Name,Department=b.Department});
 
StringBuilder sb=new StringBuilder();
foreach (var item in Users)
{
  sb.AppendLine(item.ToString());                           
}
richTextBox1.Text=sb.ToString();

最後產生如下結果
image

最後產生的結果,有點像是Inner Join
其實最近有點懶散,並沒有很仔細去看這本書
今天就先練習到這。

沒有留言:

張貼留言