【问题标题】:How to get Multiple Enumerator on same Collection of objects?如何在同一对象集合上获取多个枚举器?
【发布时间】:2014-03-19 06:36:02
【问题描述】:

我在 PartnersPool 类中有一个合作伙伴对象的集合,即列出合作伙伴。我也有实体对象。每个实体对象都包含“工作表”,其中包含合作伙伴列表,而合作伙伴列表又从 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 );

【问题讨论】:

    标签: c# iterator


    【解决方案1】:

    在 PartnerPool 类中,最好有 2 个单独的方法:

    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 然后添加到返回列表中

    【讨论】:

    • 嗯,以30个为例,合作伙伴的数量会根据一定的条件动态生成。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2013-05-04
    • 2010-10-13
    • 1970-01-01
    相关资源
    最近更新 更多