开发者

Nested Forloop with Remove method and If condition using LINQ

I want to convert the below code to LINQ or Lambda expression.

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--;
  }
}

I tried to do this:

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

but not able to figure out how to remove the price element when pr.Term!0.


Here you have:

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

Hope this helps. Cheers


Would this not work and be more concise...

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


If you want to remove price element if Term = 0 . Below is the query

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜