如何在另一个类的列表列表中使用foreach

时间:2013-03-19 22:19:53

标签: c# list foreach

public class ItemCollection
{
    List<AbstractItem> LibCollection;

    public ItemCollection()
    {
        LibCollection = new List<AbstractItem>(); 
    }

    public List<AbstractItem> ListForSearch()
    {
        return LibCollection;
    }

在另一个班级我写了这个:

public class Logic
{
    ItemCollection ITC;

    List<AbstractItem> List;

    public Logic()
    {
        ITC = new ItemCollection();   

        List = ITC.ListForSearch();    
    }

    public List<AbstractItem> search(string TheBookYouLookingFor)
    {
        foreach (var item in List)
        {
          //some code..
        }

并且foreach中的列表不包含任何内容 我需要处理此列表(此列表应与libcollection的内容相同)用于搜索方法

1 个答案:

答案 0 :(得分:0)

如果ItemCollection除了拥有List<AbstractItem>之外没有任何其他目的,那么该类应该完全删除,只需使用List<AbstractItem>

如果ItemCollection有其他目的而其他人无法访问基础List<AbstractItem>,则可以实施IEnumerable<AbstractItem>

class ItemCollection : IEnumerable<AbstractItem>
{
    List<AbstractItem> LibCollection;

    public ItemCollection() {
        this.LibCollection = new List<AbstractItem>();
    }

    IEnumerator<AbstractItem> IEnumerable<AbstractItem>.GetEnumerator() {
        return this.LibCollection.GetEnumerator();
    }

    IEnumerator System.Collections.IEnumerable.GetEnumerator() {
        return ((IEnumerable)this.LibCollection).GetEnumerator();
    }
}

class Logic
{
    ItemCollection ITC;

    public Logic() {
        ITC = new ItemCollection();
    }

    public List<AbstractItem> Search(string TheBookYouLookingFor) {
        foreach (var item in this.ITC) {
            // Do something useful
        }
        return null; // Do something useful, of course
    }
}

否则,您可能希望直接公开LibCollection并让其他代码枚举:

class ItemCollection
{
    public List<AbstractItem> LibCollection { get; private set; }

    public ItemCollection() {
        this.LibCollection = new List<AbstractItem>();
    }
}

class Logic
{
    ItemCollection ITC;

    public Logic() {
        ITC = new ItemCollection();
    }

    public List<AbstractItem> Search(string TheBookYouLookingFor) {
        foreach (var item in this.ITC.LibCollection) {
            // Do something useful
        }
        return null; // Do something useful
    }
}