[英]how do i filter nulls out of this linq query?
我有遍歷列表列表的代碼。
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查詢,以及原始的非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);
// }
// }
//}
怎么樣
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)
return Inner.resourceURL.Select(ru => FromDate(ru.location))
.Where(d => d != null)
.SelectMany(ru =>
ru.Inner.resourceURL
.Select(ru2 => AffiliateItem.From(ru2)))
原諒我沒有使用查詢語法,我只是發現方法鏈更具表現力。
另請注意,此代碼是在沒有任何IDE的情況下編碼的,因此可能會出現錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.