2013-01-03 275 views
8

我有列表,I;只需要使用LINQ/LAMBDA選擇一定的標準,基地Lists.ForEach用條件選擇使用LINQ/LAMBDA

我的代碼是

Lists.ForEach(x => x.IsAnimal == false { /* Do Something */ }); 

我收到錯誤「只有分配,電話,遞增,遞減和新對象表達式可以用作聲明」在這部分x.IsAnimal == false

我知道我們可以用一個for循環很容易實現這一點,但我想使用LINQ/LAMBDA

回答

18

瞭解更多隻要使用ToList使用的ForEach

之前
Lists.Where(x => !x.IsAnimal).ToList().ForEach(...) 
+0

+1對於那些光榮的事物替換'!' =) – Coops

+1

['Enumerable.Where'](http://msdn.microsoft.com/zh-cn/library/bb534803.aspx)的結果是'IEnumerable '。至少在BCL中,'IEnumerable '沒有'ForEach'擴展方法,所以你的代碼不會被編譯。 –

+0

哪裏不會返回'List '。 'ToList()'丟失:'Lists.Where(x =>!x.IsAnimal).ToList()。ForEach(' – nemesv

4

請在syntax of lambda expressions讀了:一個lambda表達式表示的方法; =>之前的部分是參數列表,之後的部分是返回結果的單個表達式或方法體。

您可以在方法體中添加限制:

Lists.ForEach(x => { 
        if (!x.IsAnimal) { 
         // do something 
        } 
       }); 
+3

+1因爲沒有建立一個新的列表只是爲了調用ForEach – Rawling

3

應該是這樣的:

things.Where(x => !x.IsAnimal).ToList().ForEach(x => { // do something }); 

我可以看到人們都在抱怨不得不建立新的列表中使用的ForEach。你可以做同樣的事情選擇和堅持的IEnumerable:

things.Where(x => !x.IsAnimal).Select(x => 
{ 
    // do something with it 
    return x; // or transform into something else. 
}); 
16

這是不工作,因爲你不能有false{}結構。

Lists.ForEach(x => { 
        if(x.IsAnimal){ 
         //Do Something 
        } 
      }); 
+4

+1沒有建立一個新的'List'只是爲了調用'ForEach' ... – Rawling

0

請記住,有 lists.foreach和正常的foreach之間的差異。每個「普通」使用枚舉器,因此更改迭代列表是非法的。 lists.foreach()不使用枚舉器(如果我不錯誤地說它在後臺使用索引器)可以隨時更改數組中的項目。

希望這有助於

+0

是的!在大多數情況下,只是使用' foreach「,它幾乎感覺像是一個錯誤,.NET 2.0的作者決定包含List <>。ForEach(Action <>)' –

-2

嘗試這樣的代碼:

class A { 
    public bool IsAnimal { get; set; } 
    public bool Found { get; set; } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     List<A> lst = new List<A>(); 

     lst.Add(new A() { IsAnimal = false, Found = false }); 
     lst.Add(new A() { IsAnimal = true, Found = false }); 
     lst.Add(new A() { IsAnimal = true, Found = false }); 
     lst.Add(new A() { IsAnimal = false, Found = false }); 

     // Here you first iterate to find only items with (IsAnimal == false) 
     // then from IEnumerable we need to get a List of items subset 
     // Last action is to execute ForEach on the subset where you can put your actions... 
     lst.Where(x => x.IsAnimal == false).ToList().ForEach(y => y.Found = true); 
    } 
} 
+0

Brotip,不需要'== false'和'== true' 。可以分別爲'!x.IsAnimal'和'y.Found'。 – Arran

+0

@Arran感謝您的評論,這只是爲了清晰的代碼。 –

0

如果你想使用 「的ForEach」 對不同類型的集合,你應該寫爲IEnumerable的擴展:

public static class IEnumerableExtension 
{ 
    public static void ForEach<T>(this IEnumerable<T> data, Action<T> action) 
    { 
     foreach (T d in data) 
     { 
      action(d); 
     } 
    } 
} 

使用此擴展程序,您可以在使用ForEach之前進行過濾,並且不必使用已過濾的項目形成新的列表:

lists.Where(x => !x.IsAnimal).ForEach(/* Do Something */ ); 

我prefere標準版:

foreach (var x in lists.Where(x => !x.IsAnimal)) { /* Do Something */ } 

不是很長,顯然與副作用的循環。