Csharp/C Sharp/Generics/Generic Collections — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 15:31, 26 мая 2010

Add Collection Items with IComparable interface implementation

 
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;

public class Customer : System.IComparable {
    private int _id;
    private string _name;
    private string _rating;
    private static SortOrder _order;
    public enum SortOrder {
        Ascending = 0,
        Descending = 1
    }
    public Customer(int id, string name)
        : this(id, name, "Other") {
    }
    public Customer(int id, string name, string rating) {
        this._id = id;
        this._name = name;
        this._rating = rating;
    }
    public int Id {
        get { return this._id; }
        set { this._id = value; }
    }
    public string Name {
        get { return this._name; }
        set { this._name = value; }
    }
    public string Rating {
        get { return this._rating; }
        set { this._rating = value; }
    }
    public static SortOrder Order {
        get { return _order; }
        set { _order = value; }
    }
    public override bool Equals(Object obj) {
        bool retVal = false;
        if (obj != null) {
            Customer custObj = (Customer)obj;
            if ((custObj.Id == this.Id) &&
                (custObj.Name.Equals(this.Name) &&
                (custObj.Rating.Equals(this.Rating))))
                retVal = true;
        }
        return retVal;
    }
    public override string ToString() {
        return this._id + ": " + this._name;
    }
    public int CompareTo(Object obj) {
        switch (_order) {
            case SortOrder.Ascending:
                return this.Name.rupareTo(((Customer)obj).Name);
            case SortOrder.Descending:
                return (((Customer)obj).Name).rupareTo(this.Name);
            default:
                return this.Name.rupareTo(((Customer)obj).Name);
        }
    }
}
public class CollectionTest {
    public static void Main() {
        Collection<Customer> custColl = new Collection<Customer>();
        custColl.Add(new Customer(1, "S"));
        custColl.Add(new Customer(2, "K"));
        custColl.Add(new Customer(3, "T"));
        custColl.Insert(1, new Customer(4, "Inserted Employee"));
        custColl[3] = new Customer(9, "F");
        foreach (Customer cust in custColl)
            Console.Out.WriteLine(cust);
    }
}


Add object in a hierarchy into a generic Collection

 

using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Text;
public class Chicken : Animal {
    public void LayEgg() {
        Console.WriteLine("{0} Animal.", name);
    }
    public Chicken(string newName)
        : base(newName) {
    }
}
public class Cow : Animal {
    public void Milk() {
        Console.WriteLine("{0} cow.", name);
    }
    public Cow(string newName)
        : base(newName) {
    }
}
public abstract class Animal {
    protected string name;
    public string Name {
        get {
            return name;
        }
        set {
            name = value;
        }
    }
    public Animal() {
        name = "animal";
    }
    public Animal(string newName) {
        name = newName;
    }
    public void Feed() {
        Console.WriteLine("{0} is feeding.", name);
    }
}
class Program {
    static void Main(string[] args) {
        Collection<Animal> animalCollection = new Collection<Animal>();
        animalCollection.Add(new Cow("A"));
        animalCollection.Add(new Chicken("B"));
        foreach (Animal myAnimal in animalCollection) {
            myAnimal.Feed();
        }
    }
}


Add user-defined object to generic Collection

 
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Text;
class Team {
    private string name;
    public Team(string name) {
        this.name = name;
    }
    public override string ToString() {
        return name;
    }
}
class Program {
    static void Main(string[] args) {
        Collection<Team> teams = new Collection<Team>();
        teams.Add(new Team("Ferrari"));
        teams.Add(new Team("Williams-BMW"));
        teams.Add(new Team("Bar-Honda"));
        teams.Add(new Team("McLaren-Mercedes"));
        foreach (Team t in teams) {
            Console.WriteLine(t);
        }
    }
}


Generic Collection and List

 
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
public class CollectionTest {
    public static void Main() {
        Collection<int> intCollection = new Collection<int>();
        List<String> strList = new List<String>();
        strList.Add("Val1");
        strList.Add("Val2");
        Collection<String> strCollection = new Collection<String>(strList);
        foreach (String strVal1 in strCollection)
            System.Console.WriteLine(strVal1);
        strList[0] = "Val Changed";
        foreach (String strVal2 in strCollection)
            System.Console.WriteLine(strVal2);
    }
}


Generic collection class

 
using System;
using System.Collections.Generic;
public class Bag<T> {
    private List<T> items = new List<T>();
    public void Add(T item) {
        items.Add(item);
    }
    public T Remove() {
        T item = default(T);
        if (items.Count != 0) {
            Random r = new Random();
            int num = r.Next(0, items.Count);
            item = items[num];
            items.RemoveAt(num);
        }
        return item;
    }
    public T[] RemoveAll() {
        T[] i = items.ToArray();
        items.Clear();
        return i;
    }
}
public class MainClass {
    public static void Main(string[] args) {
        Bag<string> bag = new Bag<string>();
        bag.Add("D");
        bag.Add("B");
        bag.Add("G");
        bag.Add("M");
        bag.Add("N");
        bag.Add("I");
        Console.WriteLine("Item 1 = {0}", bag.Remove());
        Console.WriteLine("Item 2 = {0}", bag.Remove());
        Console.WriteLine("Item 3 = {0}", bag.Remove());
        Console.WriteLine("Item 4 = {0}", bag.Remove());
        string[] s = bag.RemoveAll();
    }
}


Sort by Name

 
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;

public class Employee : System.IComparable {
    private int _id;
    private string _name;
    private string _rating;
    private static SortOrder _order;
    public enum SortOrder {
        Ascending = 0,
        Descending = 1
    }
    public Employee(int id, string name)
        : this(id, name, "Other") {
    }
    public Employee(int id, string name, string rating) {
        this._id = id;
        this._name = name;
        this._rating = rating;
    }
    public int Id {
        get { return this._id; }
        set { this._id = value; }
    }
    public string Name {
        get { return this._name; }
        set { this._name = value; }
    }
    public string Rating {
        get { return this._rating; }
        set { this._rating = value; }
    }
    public static SortOrder Order {
        get { return _order; }
        set { _order = value; }
    }
    public override bool Equals(Object obj) {
        bool retVal = false;
        if (obj != null) {
            Employee custObj = (Employee)obj;
            if ((custObj.Id == this.Id) &&
                (custObj.Name.Equals(this.Name) &&
                (custObj.Rating.Equals(this.Rating))))
                retVal = true;
        }
        return retVal;
    }
    public override string ToString() {
        return this._id + ": " + this._name;
    }
    public int CompareTo(Object obj) {
        switch (_order) {
            case SortOrder.Ascending:
                return this.Name.rupareTo(((Employee)obj).Name);
            case SortOrder.Descending:
                return (((Employee)obj).Name).rupareTo(this.Name);
            default:
                return this.Name.rupareTo(((Employee)obj).Name);
        }
    }
}
public class CollectionTest {
    public static void Main() {
        List<Employee> collCustList = new List<Employee>();
        collCustList.Add(new Employee(99, "H", "P"));
        collCustList.Add(new Employee(77, "B", "G"));
        collCustList.Add(new Employee(55, "B", "G"));
        collCustList.Add(new Employee(88, "B", "P"));
        collCustList.Add(new Employee(11, "L", "O"));
        foreach (Employee cust in collCustList)
            Console.Out.WriteLine(cust);
        Employee.Order = Employee.SortOrder.Ascending;
        collCustList.Sort(delegate(Employee cust1, Employee cust2) {
            return Comparer<Employee>.Default.rupare(cust1, cust2);
        });
        foreach (Employee cust in collCustList)
            Console.Out.WriteLine(cust);
        Employee.Order = Employee.SortOrder.Descending;
        collCustList.Sort(delegate(Employee cust1, Employee cust2) {
            return Comparer<Employee>.Default.rupare(cust1, cust2);
        });
        foreach (Employee cust in collCustList)
            Console.Out.WriteLine(cust);
    }
}