aronmatthew
Active member
- Joined
- Aug 5, 2019
- Messages
- 43
- Programming Experience
- Beginner
Does anyone have a List Enumerator example for generic list class. One that inherits from IEnumerator. Such that foreach can be used for generic list class.
Collection<T>
and you get that functionality for free. Is there any reason that you can't do that?as is I'm simply using a field List<T>. I am not at all familiar with the Collection class. It should work this way also.There should be no need. If you're defining your own collection class then it should inheritCollection<T>
and you get that functionality for free. Is there any reason that you can't do that?
List<T>
implements IEnumerable<T>
:IEnumerable<T>
:as is I'm simply using a field List<T>.
foreach
loop will already work, so what problem are you actually trying to solve? It's not clear that there is one. What exactly is it that you want to do that you are unable to?using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class MyCollection<T> : IEnumerable<T>
{
private readonly List<T> _items = new List<T>();
public void Add(T item)
{
_items.Add(item);
}
public bool Remove(T item)
{
return _items.Remove(item);
}
public int Count => _items.Count;
public T this[int index]
{
get => _items[index];
set => _items[index] = value;
}
// Implement GetEnumerator to allow enumeration
public IEnumerator<T> GetEnumerator()
{
return _items.GetEnumerator();
}
// Explicit implementation of IEnumerable for non-generic use
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
class Program
{
static void Main()
{
var myCollection = new MyCollection<string>();
myCollection.Add("apple");
myCollection.Add("banana");
myCollection.Add("apricot");
var filtered = myCollection.Where(s => s.StartsWith("a"));
foreach (var item in filtered)
{
Console.WriteLine(item);
}
}
}
List<T>
internally - then don't. If you can't simply use a generic List directly because you need some custom functionality, do as I said and inherit the Collection<T>
class. That way, all the standard internals are provided for nothing, including full enumerable functionality, and you just add the specific custom functionality you need. If you know nothing about that class then the obvious first step is to follow the link I provided and read about it.Collection<T>
class is implemented by looking at the reference source code:public class Collection<T>: IList<T>, IList, IReadOnlyList<T>
{
IList<T> items;
:
public Collection() {
items = new List<T>();
}
public Collection(IList<T> list) {
if (list == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list);
}
items = list;
}
: