我的代码遍历列表列表。
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);
// }
// }
//}
答案 0 :(得分: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)
答案 1 :(得分:0)
return Inner.resourceURL.Select(ru => FromDate(ru.location))
.Where(d => d != null)
.SelectMany(ru =>
ru.Inner.resourceURL
.Select(ru2 => AffiliateItem.From(ru2)))
请原谅我没有使用查询语法,我发现方法链更具表现力。
另请注意,这是在没有任何IDE的情况下编码的,因此可能会出错。