Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable collection to List

Tags:

c#

.net

I've written a CustomerCollection class, which implements the IEnumerable and IEnumerator interfaces. Now I want the CustomerCollection class object to be searchable by Where() And Find() function and also would like to get a List object of type Customer From the CustomerCollection class. Please help. Also, is the implementation of the interfaces right.

public class Customer
{
    private int _CustomerID;
    private string _CustomerName;

    public Customer(int customerID)
    {
        this._CustomerID = customerID;
    }

    public int CustomerID
    {
        get
        {
            return _CustomerID;
        }
        set
        {
            _CustomerID = value;
        }
    }

    public string CustomerName
    {
        get
        {
            return _CustomerName;
        }
        set
        {
            _CustomerName = value;
        }
    }
}

public class CustomerController
{
    public ArrayList PopulateCustomer()
    {
        ArrayList Temp = new ArrayList();

        Customer _Customer1 = new Customer(1);
        Customer _Customer2 = new Customer(2);

        _Customer1.CustomerName = "Soham Dasgupta";
        _Customer2.CustomerName = "Bappa Sarkar";

        Temp.Add(_Customer1);
        Temp.Add(_Customer2);

        return Temp;
    }
}

public class CustomerCollection : IEnumerable, IEnumerator
{
    ArrayList Customers = null;
    IEnumerator CustomerEnum = null;

    public CustomerCollection()
    {
        this.Customers = new CustomerController().PopulateCustomer();
        this.CustomerEnum = Customers.GetEnumerator();
    }

    public void SortByName()
    {
        this.Reset();
    }

    public void SortByID()
    {
        this.Reset();
    }

    public IEnumerator GetEnumerator()
    {
        return (IEnumerator)this;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return (IEnumerator)this;
    }

    public void Reset()
    {
        CustomerEnum.Reset();
    }

    public bool MoveNext()
    {
        return CustomerEnum.MoveNext();
    }

    public object Current
    {
        get
        {
            return (Customer)CustomerEnum.Current;
        }
    }

}
like image 750
Soham Dasgupta Avatar asked Dec 29 '22 08:12

Soham Dasgupta


1 Answers

You can call Cast<Customer>() on your IEnumerable which will give you an IEnumerable<Customer>, or just implement IEnumerable<Customer> to begin with. LINQ is almost entirely hooked into IEnumerable<T>, not IEnumerable. Once you did that you'd get all the LINQ to objects goodness for free.

like image 147
Matt Greer Avatar answered Jan 12 '23 19:01

Matt Greer