2011-03-31 35 views
0

我有迭代列表的代碼。如何過濾這個linq查詢中的空值?

public static AffiliateList FromDate(string date) 
    { 
     Console.WriteLine("calling affiliates by date for " + date); 
     AffiliateList al; 
     try 
     { 
      al = new AffiliateList(DirectTrackXmlUtility.AffilaitesByDate(date)); 
     } 
     catch (Exception) 
     { 
      return null; 
     } 
     return al; 
    } 

    public override IEnumerator<AffiliateItem> GetEnumerator() 
    { 
     return (from ru in Inner.resourceURL 
       select ru.location 
       into date select FromDate(date) 
       into listForDate from ru2 in listForDate.Inner.resourceURL 
       select AffiliateItem.From(ru2)). 
      GetEnumerator(); 
    } 

問題:如何修改處理FromDate返回null的代碼?

注意:我永遠都不會想出如何編寫這個查詢,但是我的嵌套foreach循環爲我重新做了更清晰的工作,現在我很感興趣,看看我能否使它工作...

更新:這是最終的linq查詢,以及最初的non-linq方式註釋掉。

 return (from ru in Inner.resourceURL 
       select ru.location 
       into date select FromDate(date) 
       into listForDate where listForDate != null from ru2 in listForDate.Inner.resourceURL 
       select AffiliateItem.From(ru2)).GetEnumerator(); 
     //foreach (resourceListResourceURL ru in Inner.resourceURL) 
     //{ 
     // string date = ru.location; 
     // AffiliateList listForDate = FromDate(date); 
     // if (listForDate != null) 
     // { 
     //  foreach (var ru2 in listForDate.Inner.resourceURL) 
     //  { 
     //   yield return AffiliateItem.From(ru2); 
     //  } 
     // } 
     //} 
+1

你能告訴我foreach循環嗎?我認爲創建一個LINQ查詢比從那個...更容易。 – Femaref 2011-03-31 22:15:50

+1

您想如何處理FromDate爲空?跳過它?使用默認日期? – 2011-03-31 22:17:08

+3

難道你不能使用'using'代替try/catch嗎? – 2011-03-31 22:19:43

回答

0
return Inner.resourceURL.Select(ru => FromDate(ru.location)) 
         .Where(d => d != null) 
         .SelectMany(ru => 
            ru.Inner.resourceURL 
             .Select(ru2 => AffiliateItem.From(ru2))) 

原諒我沒有使用查詢語法,我只要找到方法鏈更富於表現力。

還要注意,這是沒有任何IDE編碼,所以有可能出現錯誤。

1

如何

int date select (FromDate(date) ?? new AffiliateList()) 

from ru in Inner.resourceURL 
select ru.location into date 
select FromDate(date) into listForDate 
where listForDate != null 
from ru2 in listForDate.Inner.resourceURL 
select AffiliateItem.From(ru2)