Home > Development > Basic List Class In C#

Basic List Class In C#


using System;
using System.Linq;

namespace GenericExamples
{
    public class List<T>
    {
        private T[] _items;
        private int _currentposition = -1;
        private int _size = 10;

        public List()
            : this(10)
        {
        }

        public List(int size)
        {
            this._size = size;
            _items = new T[size];
        }

        public void Add(T item)
        {
            if (_currentposition == _items.Length - 1)
            {
                T[] temp = new T[_size * 2];
                Array.Copy(_items, temp, _size);
                _items = temp;
                _size *= 2;
            }
            _items[++_currentposition] = item;
        }

        public int Count
        {
            get { return _size; }
        }

        public int Capacity
        {
            get { return _items.Length; }
        }

        public void Sort()
        {
            Array.Sort(_items);
        }


        public void Print()
        {
            foreach (var item in _items)
            {
                Console.WriteLine(item);
            }
        }

        public bool Contains(Func<T,bool> filter)
        {
            return _items.Any(filter);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<int> ints = new List<int>();
            
            for(int i = 9; i >= 0; i--)
            {
                ints.Add(i);
            }

            ints.Print();

            Console.WriteLine("Size:{0}, Capacity: {1}",ints.Count, ints.Capacity);

            ints.Sort();
            ints.Print();

            Console.WriteLine("Item contains 11: {0} items contains 9: {1}", ints.Contains(x => x == 11), ints.Contains(x => x == 9));
           
            ints.Add(11);
            ints.Add(12);

            Console.WriteLine("Size:{0}, Capacity: {1}", ints.Count, ints.Capacity);

            ints.Sort();
            ints.Print();
            
            Console.ReadKey();

        }
    }
}

Blair

Advertisements
Categories: Development Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: