如何在同一个对象集合上获取Multiple Enumerator?

时间:2014-03-19 06:36:02

标签: c# iterator

我在PartnersPool类中有一组Partner对象,即List合作伙伴。我也有Entity对象。每个实体对象包含" Sheet"其中包含从PartnerPool中读取的合作伙伴列表。

我希望枚举ParnerPool中的合作伙伴并获得一个枚举器,以便我可以从我离开该特定实体的位置开始。不同的实体将枚举PartnerPool并且每个实体都拥有它自己的枚举器。我不想多次创建合作伙伴池来获取多个枚举器。

所以我想做以下事情。假设我有100个合作伙伴:

//Create a Enumerator.
var Enumerator<Partner> enumeratorForEntity1;
//Create first entity 
var entity1 = new entity();
//following call gets only first 30 patners.
sheet.PartnerList = PartnerPool.GetOnlyThirtyPartnerDataAndReturnEnumerator(out Enumerator<Partner> enumeratorForEntity1 );
//Now create entity2 and enumerator for it.
var Enumerator<Partner> enumeratorForEntity2;
var entity2 = new entity();
//following method call should return the first 30 partners also.
//that is it should return brand new enumerator.
sheet.PartnerList = PartnerPool.GetOnlyThirtyPartnerDataAndReturnEnumerator(out Enumerator<Partner> enumeratorForEntity2 );

//Now if I again use the first enumerator i.e. "enumeratorForEntity1" I should get the next 30 partners that is, from 30 to 60.
sheet.PartnerList = PartnerPool.GetOnlyThirtyPartnerDataAndReturnEnumerator(out Enumerator<Partner> enumeratorForEntity1 );

1 个答案:

答案 0 :(得分:0)

在类PartnerPool中,如果您有两种不同的方法,那就更好了:

public List<Partner> GetOnlyThirtyPartnerDataAndReturnEnumerator(out Enumerator<Partner> enumerator) { /*Do whatever you are doing right now*/ }
public List<Partner> GetNextThirtyPartnerData(Enumerator<Partner> enumerator) { /*Use the enumerator to continue looping on the list*/ }

在第二个方法上,只需调用enumerator.MoveNext,获取enumerator.Current然后添加到返回的列表