2010-06-04 41 views
2

由於我對LINQ的知識仍然有限,我想我會問如何簡化這個操作。我正在嘗試編寫一個從列表中選擇客戶並對結果執行一些操作的語句。如何對.FindAll()的結果執行操作

說我有:

public List<Customer> Customers 

Customers.FindAll(delegate(Customer c) { return c.Category == "A"; }); 

現在說我要帶所有那些類別==「A」的客戶,並打印其c.Names或設置c.Value =「高」。

有沒有一種快速的方法來實現這一點,而不必將結果放在另一個列表中並遍歷每一個?

回答

4

使用LINQ Where而不是FindAll

foreach (var c in Customers.Where(c => c.Category == "A")) 
{ 
    Console.WriteLine(c.Name); 
    c.Value = "High"; 
} 

應該是更高效的這種方式,因爲它不必創建一個新的列表。

3

你可以這樣做:

Customers.FindAll(delegate(Customer c) { return c.Category == "A"; }) 
    .ForEach(c => Console.WriteLine(c.Name)); 
2

你可以這樣做:

public List<Customer> Customers 

Customers.FindAll(delegate(Customer c) { return c.Category == "A"; }).ForEach(c => Console.WriteLine(c.Names)); 
相關問題