2011-07-06 26 views
1

我想將下面的代碼轉換爲LINQ或Lambda表達式。嵌套Forloop與刪除方法和如果條件使用LINQ

for (int indexprod = 0; indexprod < tempProduct.Count; indexprod++) 
{ 
    for (int index = 0; index < tempProduct[indexprod].Prices.Count; index++) 
    { 
    if (tempProduct[indexprod].Prices[index].Term == null || tempProduct[indexprod].Prices[index].Term == 0) 
    { 
     tempProduct[indexprod].Prices.Remove(tempProduct[indexprod].Prices[index]); 
     index--; 
    } 
    } 

    if (tempProduct[indexprod].Prices.Count == 0) 
    { 
    tempProduct.Remove(tempProduct[indexprod]); 
    indexprod--; 
    } 
} 

儘快提供幫助。

我試着這樣做:

List<Product> tempprod1= (from p in products 
        from pr in p.Prices 
        where pr.Term == 0 
        select p).ToList<Product>(); 

,但無法弄清楚如何去除價格因素時pr.Term 0!

感謝,

回答

1

這裏有:

tempProduct 
    .ForEach(p => p.Prices.RemoveAll(price => (price.Term ?? 0)==0)) 
    .RemoveAll(p => p.Prices.Count == 0); 

希望這有助於。歡呼聲

+0

產品這個工作的一半。我看不到.RemoveAll。 –

0

這會不會工作,更簡潔...

tempProduct.RemoveAll(p => p.Prices.Count == 0); 
+0

感謝響應,但是這是不行的,我必須刪除所有這些都Price.Term == 0 –

0

如果您想刪除價格元素,如果Term = 0。下面是查詢

tempProduct.ForEach(p=> p.Prices.Remove(p.Prices.ToList().ToList().Where(x => x.Term == 0).FirstOrDefault()));