我正在解决一个问题,我需要一次提供一个项目给消费者,并将计数器向前移动,以便下一个项目,等等,直到用完项目为止。我想出了代码的初稿(见下文)。底层数据结构包含一个字典,其中包含字符串作为其键,并将另一个字典作为其值,该字典包含类型实体的对象。
我有一种感觉,我确实需要在某种程度上保持状态,所以我尝试使用产返回语句,但不知道如何将它粘合在一起。此外,我认为使用前端/迭代器可能需要调整,因为使用者将调用GetNextItem(),直到它返回false(意味着用完项)。
private static Dictionary<string, Dictionary <uint,Entity>> dt;
private uint localCounter=0 , globalCounter = 0;
public Entity GetNextItem()
{
foreach (string key in dt.Keys )
{
if (MoveCounters(key)) //counter is moved, so process the next item
{
yield return dt[key][localCounter];
}
}
}
private bool MoveCounters(string key)
{
if (++globalCounter > dt.Count) return false; //hit the limit
if (++localCounter > dt[key].Count)
{
globalCounter++;
return true;
}
localCounter++;
return true;
}
}
public class Entity
{
Dictionary<string, string> dtValues; //contains values from CSV file.
}发布于 2014-06-06 20:57:10
当您移动到下一个子列表时,您未能将localCounter重置为零。
也就是说,你可以更容易地做到这一点:
foreach (var subdt in dt.Values)
foreach (var item in subdt.Values)
yield return item;但是使用LINQ SelectMany更容易
return dt.Values.SelectMany(subdt => subdt.Values);请注意,最后一个不使用yield return,因为LINQ生成可枚举的,您只需返回它。
如果您也想记录密钥和计数器,请尝试如下所示:
int iList = 0;
foreach( var subdt in dt ) {
/* log iList, subdt.Key */
int iItem = 0;
foreach( var item in subdt.Value ) {
/* log iItem, item.Key */
++iItem;
yield return item.Value;
}
++iList;
}https://stackoverflow.com/questions/24090352
复制相似问题