2008年8月4日星期一

LINQ : Using Lambda Expression to AddRange()

在LINQ中使用Lambda Expression,我們可以有效地extract出Anonymous Types中的values.

Example :
public List<string> GetList()
{
List<string> pList = new List<string>();
DataClasses_Store DataContext = new DataClasses_Store();
//Select the customer where live in "HongKong" and Take 100 records
var select = (from c in DataContext.customer_info
where c.customer_location.Equals("HongKong")
orderby c.reg_date descending
select new { c.customer_id , c.customer_name } ).Take(100);
//Fill the List
foreach (var s in select)
{
pList.Add(c.customer_id + " " + c.customer_name);
}
return pList;
}

使用Foreach方法都是一般網上Example做法,但是我們可以使用Lambda Expression並轉換成IEnumerable達至AddRange的要求。

public List<string> GetList()
{
List<string> pList = new List<string>();
DataClasses_Store DataContext = new DataClasses_Store();
//Select the customer where live in "HongKong" and Take 100 records
var select = (from c in DataContext.customer_info
where c.customer_location.Equals("HongKong")
orderby c.reg_date descending
select new { c.customer_id , c.customer_name } ).Take(100);
//Fill the List
pList.AddRange(select.Select(p => p.customer_id + " " + p.customer_name).AsEnumerable());
return pList;
}

沒有留言:

發佈留言