繁体   English   中英

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

[英]How to use foreach on a list of lists that on another class

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相同),以用于搜索方法

如果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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM