Search code examples
c#ienumerable

IEnumerable does not allow access to sub items


To make a long story short. I have the following code:

class MyList : IEnumerable
{
    private List<string> T1 = new List<string>();
    private List<string> T2 = new List<string>();
    private List<string> T3 = new List<string>();
    public List<string> Name { set { T1 = value; } get { return T1; } }
    public List<string> DataType { set { T2 = value; } get { return T2; } }
    public List<string> Nullable { set { T3 = value; } get { return T3; } }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return (IEnumerator)GetEnumerator();
    }
    public MyList<List<string>, List<string>, List<string>> GetEnumerator()
    {
        return new MyList<List<string>, List<string>, List<string>>(T1, T2, T2);
    }
}

What I want is to access it like this:

       MyList ml = new MyList();
       foreach (var item in ml)
       {
           str = item.Name;
       }

It does not let me access the subitem, like item.Name, or item.DataType.


Solution

  • If you really want to expose the functionality you describe (3 lists collectively representing a set of items) you can do it, but you still need to expose a new type for the benefit of your enumerator.

    class MyItem 
    {
        public string Name { get; set; }
        public string DataType { get; set; }
        public bool Nullable { get; set; }
    }
    
    class MyList : IEnumerable<MyItem>
    {
        public List<string> Names { get; set; }
        public List<string> DataTypes { get; set; }
        public List<bool> Nullables { get; set; }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    
        public IEnumerator<MyItem> GetEnumerator()
        {
            // assuming all lists are the same length
            for (int i = 0; i < Names.Count; i++)
                yield return new MyItem {
                    Name = Names[i],
                    DataType = DataTypes[i],
                    Nullable = Nullables[i]
                };
        }
    }
    

    Now you can do:

    MyList ml = new MyList();
    ml.Names = new [] { "AccountNum", "Value", "Owner" } .ToList();
    ml.DataTypes = new [] { "nvarchar(50)", "decimal(14,6)", "nvarchar(50)" } .ToList();
    ml.Nullables = new [] { false, false, true } .ToList();
    
    foreach (var item in ml)
    {
        str = item.Name;
    }