2014-10-01 76 views
0

我想下面的代码转换为LINQ的财产:LINQ查询来更新列表

for (int i = 0; i < List.Count;i++) 
       { 
        List[i].IsActive = false; 
        if(List[i].TestList != null) 
        { 
         for(int j = 0;j<List[i].TestList.Count;j++) 
         { 
          List[i].TestList[j].IsActive = false; 
         } 
        } 
       } 

我尝试以下查询:

(from s in List select s).ToList().ForEach((s) => 
         { 
          s.IsActive = false; 
          (from t in s.TestList where t != null select t).ToList().ForEach((t) => 
           { 
            t.IsActive = false; 
           }); 
         }); 

,但我得到一个错误,当TestList是在列表中为null。我不确定我在这里做错了什么。

+2

''之前收集这所有项目,其中T是'null' 。也许'(从s.TestList中的t,其中t!= null选择t)' – Fabio 2014-10-01 05:39:34

+0

我的错误,它是t!= null我输入错了。但是,我仍然得到错误。 – perplexedDev 2014-10-01 17:08:37

回答

1

如果您的原始(无LINQ)代码工作。
然后你错过了一个线,检查TestList的空(在s.TestList其中t在t == NULL选择T)迭代项目

(from s in List select s).ToList().ForEach((s) => 
    { 
     s.IsActive = false; 
     if(s.TestList != null) //This check of TestList was missing 
      (from t in s.TestList where t != null select t).ToList().ForEach((t) => 
         { 
            t.IsActive = false; 
         }); 
    }); 
1

您选择列表是空

where t == null 

如果该条件是

where t != null 
0

一个简单的方法。无需检查空值。

s.ForEach((x)=> 
    { 
     x.IsActive = false; 
     x.TestList.Foreach((t)=>{t.IsActive = false}); 

    }); 
0

,因为它看起来像你停用所有嵌套TestList项目你不一定需要一个内环。你可以只具有两个独立的回路:

foreach(var item in List) 
    item.IsActive = false; 

foreach(var item in List.Where(x => x.TestList != null).SelectMany(x => x.TestList)) 
    item.IsActive = false; 

注意SelectMany“变平”内部名单成一个单一的IEnumerable<T>