Csharp/CSharp Tutorial/Data Structure/List

Материал из .Net Framework эксперт
Версия от 12:15, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Compact Code for looping through the List with delegate

using System;
using System.Collections.Generic;
using System.ruponentModel;
    class UglyButCompactCode
    {
        static void Main()
        {
            List<int> x = new List<int>();
            x.Add(5);
            x.Add(10);
            x.Add(15);
            x.Add(20);
            x.Add(25);
            x.ForEach(delegate(int n) { Console.WriteLine(Math.Sqrt(n)); }); 
        }
    }

Converting a list from list of string to list of int

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
public class MainClass
{
    public static void Main()
    {
        List<string> stringList1 = new List<string>(new string[] { "99", "182", "15" });
        List<int> intList1 = stringList1.ConvertAll<int>(Convert.ToInt32);
    }
}

Converting a list: user defined converting function

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
public class MainClass
{
    private static int ConvertStringToInt(string input)
    {
        int result;
        if (!int.TryParse(input, out result))
            result = -1;
        return result;
    }
    public static void Main()
    {
        List<string> stringList2 = new List<string>(new string[] { "99", "182", "invalid", "15" });
        List<int> intList2 = stringList2.ConvertAll<int>(ConvertStringToInt);
    }
}

Implement IComparable to use List.Sort

using System;
using System.Collections.Generic;
    public class Employee : IComparable<Employee>
    {
        private int empID;
        public Employee(int empID)
        {
            this.empID = empID;
        }
        public override string ToString()
        {
            return empID.ToString();
        }
        public bool Equals(Employee other) 
        {
            if (this.empID == other.empID)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public int CompareTo(Employee rhs)
        {
            return this.empID.rupareTo(rhs.empID);
        }
    }
    public class Tester
    {
        static void Main()
        {
            List<Employee> empArray = new List<Employee>();
            List<Int32> intArray = new List<Int32>();
            for (int i = 0; i < 5; i++)
            {
                empArray.Add(new Employee(i));
                intArray.Add(i);
            }
            intArray.Sort();
            for (int i = 0; i < intArray.Count; i++)
            {
                Console.Write("{0} ", intArray[i].ToString());
            }
            empArray.Sort();
            for (int i = 0; i < empArray.Count; i++)
            {
                Console.Write("{0} ", empArray[i].ToString());
            }
        }
    }

List Convert All

using System;
using System.Collections.Generic;
using System.ruponentModel;
    class ListConvertAll
    {
        static double TakeSquareRoot(int x)
        {
            return Math.Sqrt(x);
        }
        static void Main()
        {
            List<int> integers = new List<int>();
            integers.Add(1);
            integers.Add(2);
            integers.Add(3);
            integers.Add(4);
            Converter<int, double> converter = TakeSquareRoot;
            List<double> doubles = integers.ConvertAll<double>(converter);
            foreach (double d in doubles)
            {
                Console.WriteLine(d);
            }
        }
    }

List Filtering With Linq

using System.Text;
using System.Xml.Linq;
using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Linq;
using System.Collections;
public class Product
{
    string name;
    public string Name
    {
        get { return name; }
    }
    decimal price;
    public decimal Price
    {
        get { return price; }
    }
    public Product(string name, decimal price)
    {
        this.name = name;
        this.price = price;
    }

    public override string ToString()
    {
        return string.Format("{0}: {1}", name, price);
    }
}
class ListFilteringWithLinq
{
    public static List<Product> GetSampleProducts()
    {
        List<Product> list = new List<Product>();
        list.Add(new Product("C", 9.99m));
        list.Add(new Product("A", 1.99m));
        list.Add(new Product("F", 2.99m));
        list.Add(new Product("S", 3.99m));
        return list;
    }
    static void Main()
    {
        List<Product> products = GetSampleProducts();
        var filtered = from Product p in products
                       where p.Price > 10
                       select p;
        foreach (Product product in filtered)
        {
            Console.WriteLine(product);
        }
    }
}

List.ForEach

using System;
using System.Collections.Generic;
using System.ruponentModel;
    class Primes
    {
        static void Main()
        {
            List<int> candidates = new List<int>();         
            for (int i=2; i <= 100; i++)                    
            {                                               
                candidates.Add(i);                          
            }                                               
            for (int factor=2; factor <= 10; factor++)      
            {                                               
                candidates.RemoveAll (delegate(int x)       
                    { return x>factor && x%factor==0; }     
                );                                          
            }
            candidates.ForEach (delegate(int prime)
                { Console.WriteLine(prime); }      
            );                                            
        }
    }

List Joining Ordering And Filtering With Linq

using System.Text;
using System.Xml.Linq;
using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Linq;

    class ProductWithSupplierID
    {
        public string Name { get; private set; }
        public decimal Price { get; private set; }
        public int SupplierID { get; private set; }
        public ProductWithSupplierID(string name, decimal price)
        {
            Name = name;
            Price = price;
        }
        ProductWithSupplierID()
        {
        }
        public static List<ProductWithSupplierID> GetSampleProducts()
        {
            return new List<ProductWithSupplierID>
            {
                new ProductWithSupplierID { Name="C", Price = 9.99m, SupplierID=1 },
                new ProductWithSupplierID { Name="A", Price=14.99m, SupplierID=2 },
                new ProductWithSupplierID { Name="F", Price=13.99m, SupplierID=1 },
                new ProductWithSupplierID { Name="S", Price=10.99m, SupplierID=3}
            };
        }
        public override string ToString()
        {
            return string.Format("{0}: {1}", Name, Price);
        }
    }
    class Supplier
    {
        public string Name { get; private set; }
        public int SupplierID { get; private set; }
        Supplier()
        {
        }
        public static List<Supplier> GetSampleSuppliers()
        {
            return new List<Supplier>
            {
                new Supplier { Name="S", SupplierID=1 },
                new Supplier { Name="C", SupplierID=2 },
                new Supplier { Name="B", SupplierID=3 }
            };
        }
    }    
    class ListJoiningOrderingAndFilteringWithLinq
    {
        static void Main()
        {
            List<ProductWithSupplierID> products = ProductWithSupplierID.GetSampleProducts();
            List<Supplier> suppliers = Supplier.GetSampleSuppliers();
            var filtered = from p in products
                           join s in suppliers
                           on p.SupplierID equals s.SupplierID
                           where p.Price > 10
                           orderby s.Name, p.Name
                           select new
                           {
                               SupplierName = s.Name,
                               ProductName = p.Name
                           };
            foreach (var v in filtered)
            {
                Console.WriteLine("Supplier={0}; Product={1}",
                                  v.SupplierName, v.ProductName);
            }
        }
    }

List Order With Extension Method

using System.Text;
using System.Xml.Linq;
using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Linq;
    class Product
    {
        public string Name { get; private set; }
        public decimal Price { get; private set; }
        public Product(string name, decimal price)
        {
            Name = name;
            Price = price;
        }
        Product()
        {
        }
        public static List<Product> GetSampleProducts()
        {
            return new List<Product>
            {
                new Product { Name="C", Price=9.99m },
                new Product { Name="A", Price=14.99m },
                new Product { Name="F", Price=13.99m },
                new Product { Name="S", Price=10.99m}
            };
        }
        public override string ToString()
        {
            return string.Format("{0}: {1}", Name, Price);
        }
    }
    class ListOrderWithExtensionMethod
    {
        static void Main()
        {
            List<Product> products = Product.GetSampleProducts();
            foreach (Product product in products.OrderBy(p => p.Name))
            {
                Console.WriteLine(product);
            }
        }
    }

List Query With Delegates

using System;
using System.Collections;
using System.Collections.Generic;
using System.ruponentModel;
    public class Product
    {
        string name;
        public string Name
        {
            get { return name; }
        }
        decimal price;
        public decimal Price
        {
            get { return price; }
        }
        public Product(string name, decimal price)
        {
            this.name = name;
            this.price = price;
        }
        public static List<Product> GetSampleProducts()
        {
            List<Product> list = new List<Product>();
            list.Add(new Product("C", 9.99m));
            list.Add(new Product("A", 1.99m));
            list.Add(new Product("F", 2.99m));
            list.Add(new Product("S", 3.99m));
            return list;
        }
        public override string ToString()
        {
            return string.Format("{0}: {1}", name, price);
        }
    }

    class ListQueryWithDelegates
    {
        static void Main()
        {
            List<Product> products = Product.GetSampleProducts();
            Predicate<Product> test = delegate(Product p)
                { return p.Price > 10m; };
            List<Product> matches = products.FindAll(test);
            Action<Product> print = delegate(Product p)
                { Console.WriteLine(p); };
            matches.ForEach(print);
        }
    }

List Query With Delegates Compact

using System;
using System.Collections;
using System.Collections.Generic;
using System.ruponentModel;
    public class Product
    {
        string name;
        public string Name
        {
            get { return name; }
        }
        decimal price;
        public decimal Price
        {
            get { return price; }
        }
        public Product(string name, decimal price)
        {
            this.name = name;
            this.price = price;
        }
        public static List<Product> GetSampleProducts()
        {
            List<Product> list = new List<Product>();
            list.Add(new Product("C", 9.99m));
            list.Add(new Product("A", 1.99m));
            list.Add(new Product("F", 2.99m));
            list.Add(new Product("S", 3.99m));
            return list;
        }
        public override string ToString()
        {
            return string.Format("{0}: {1}", name, price);
        }
    }

    class ListQueryWithDelegatesCompact
    {
        static void Main()
        {
            List<Product> products = Product.GetSampleProducts();
            products.FindAll(delegate(Product p) { return p.Price > 10; })
                    .ForEach(delegate(Product p) { Console.WriteLine(p); });
        }
    }

List Query With Lambda Expression

using System.Text;
using System.Xml.Linq;
using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Linq;
    class Product
    {
        public string Name { get; private set; }
        public decimal Price { get; private set; }
        public Product(string name, decimal price)
        {
            Name = name;
            Price = price;
        }
        Product()
        {
        }
        public static List<Product> GetSampleProducts()
        {
            return new List<Product>
            {
                new Product { Name="C", Price=9.99m },
                new Product { Name="A", Price=14.99m },
                new Product { Name="F", Price=13.99m },
                new Product { Name="S", Price=10.99m}
            };
        }
        public override string ToString()
        {
            return string.Format("{0}: {1}", Name, Price);
        }
    }
    class ListQueryWithLambdaExpression
    {
        static void Main()
        {
            List<Product> products = Product.GetSampleProducts();
            foreach (Product product in products.Where(p => p.Price > 10))
            {
                Console.WriteLine(product);
            }
        }
    }

List Sort With Comparer

using System;
using System.Collections.Generic;
using System.Collections;
using System.ruponentModel;
    public class Product
    {
        string name;
        public string Name
        {
            get { return name; }
        }
        decimal price;
        public decimal Price
        {
            get { return price; }
        }
        public Product(string name, decimal price)
        {
            this.name = name;
            this.price = price;
        }
        public static List<Product> GetSampleProducts()
        {
            List<Product> list = new List<Product>();
            list.Add(new Product("C", 9.99m));
            list.Add(new Product("A", 1.99m));
            list.Add(new Product("F", 2.99m));
            list.Add(new Product("S", 3.99m));
            return list;
        }
        public override string ToString()
        {
            return string.Format("{0}: {1}", name, price);
        }
    }

    class ListSortWithComparer
    {
        class ProductNameComparer : IComparer<Product>
        {
            public int Compare(Product first, Product second)
            {
                return first.Name.rupareTo(second.Name);
            }
        }
        static void Main()
        {
            List<Product> products = Product.GetSampleProducts();
            products.Sort(new ProductNameComparer());
            foreach (Product product in products)
            {
                Console.WriteLine(product);
            }
        }
    }

List Sort With Comparison Delegate

using System;
using System.Collections;
using System.Collections.Generic;
using System.ruponentModel;
    public class Product
    {
        string name;
        public string Name
        {
            get { return name; }
        }
        decimal price;
        public decimal Price
        {
            get { return price; }
        }
        public Product(string name, decimal price)
        {
            this.name = name;
            this.price = price;
        }
        public static List<Product> GetSampleProducts()
        {
            List<Product> list = new List<Product>();
            list.Add(new Product("C", 9.99m));
            list.Add(new Product("A", 1.99m));
            list.Add(new Product("F", 2.99m));
            list.Add(new Product("S", 3.99m));
            return list;
        }
        public override string ToString()
        {
            return string.Format("{0}: {1}", name, price);
        }
    }
    class ListSortWithComparisonDelegate
    {
        static void Main()
        {
            List<Product> products = Product.GetSampleProducts();
            products.Sort(delegate(Product first, Product second)
                { return first.Name.rupareTo(second.Name); }
            );
            foreach (Product product in products)
            {
                Console.WriteLine(product);
            }
        }
    }

Obtaining a read-only copy of a list

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
public class MainClass
{
    public static void Main()
    {
        List<int> intList = new List<int>(new int[] { 3, 5, 15, 1003, 25 });
        ReadOnlyCollection<int> roList = intList.AsReadOnly();
    }
}

Using external method to pass into Find method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Xml.Linq;
    class Program
    {
        static void Main(string[] args)
        {
            List<string> myList = new List<string>();
            myList.Add("A");
            myList.Add("B");
            myList.Add("C");
            myList.Add("D");
            string vanilla = myList.Find(FindVanilla);
            Console.WriteLine(vanilla);
        }
        public static bool FindVanilla(string icecream)
        {
            return icecream.Equals("B");
        }        
    }

Using the Action<T> delegate

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
public class MainClass
{
    public static void Main()
    {
        List<int> intList = new List<int>(new int[] { 3, 5, 15, 1003, 25 });
        
        intList.ForEach(delegate(int x) { Console.WriteLine(x); });
    }
}
3
5
15
1003
25

Vector extends List

using System;
using System.Collections.Generic;
using System.Text;
public static class VectorDelegates {
    public static int Compare(Vector x, Vector y) {
        if (x.R > y.R) {
            return 1;
        } else if (x.R < y.R) {
            return -1;
        }
        return 0;
    }
    public static bool TopRightQuadrant(Vector target) {
        if (target.Theta >= 0.0 && target.Theta <= 90.0) {
            return true;
        } else {
            return false;
        }
    }
}
public class Vectors : List<Vector> {
    public Vectors() {
    }
    public Vectors(IEnumerable<Vector> initialItems) {
        foreach (Vector vector in initialItems) {
            Add(vector);
        }
    }
    public string Sum() {
        StringBuilder sb = new StringBuilder();
        Vector currentPoint = new Vector(0.0, 0.0);
        sb.Append("origin");
        foreach (Vector vector in this) {
            sb.AppendFormat(" + {0}", vector);
            currentPoint += vector;
        }
        sb.AppendFormat(" = {0}", currentPoint);
        return sb.ToString();
    }
}
public class Vector {
    public double? R = null;
    public double? Theta = null;
    public double? ThetaRadians {
        get {
            return (Theta * Math.PI / 180.0);
        }
    }
    public Vector(double? r, double? theta) {
        if (r < 0) {
            r = -r;
            theta += 180;
        }
        theta = theta % 360;
        R = r;
        Theta = theta;
    }
    public static Vector operator +(Vector op1, Vector op2) {
        try {
            double newX = op1.R.Value * Math.Sin(op1.ThetaRadians.Value)
               + op2.R.Value * Math.Sin(op2.ThetaRadians.Value);
            double newY = op1.R.Value * Math.Cos(op1.ThetaRadians.Value)
               + op2.R.Value * Math.Cos(op2.ThetaRadians.Value);
            double newR = Math.Sqrt(newX * newX + newY * newY);
            double newTheta = Math.Atan2(newX, newY) * 180.0 / Math.PI;
            return new Vector(newR, newTheta);
        } catch {
            return new Vector(null, null);
        }
    }
    public static Vector operator -(Vector op1) {
        return new Vector(-op1.R, op1.Theta);
    }
    public static Vector operator -(Vector op1, Vector op2) {
        return op1 + (-op2);
    }
    public override string ToString() {
        string rString = R.HasValue ? R.ToString() : "null";
        string thetaString = Theta.HasValue ? Theta.ToString() : "null";
        return string.Format("({0}, {1})", rString, thetaString);
    }
}
class Program {
    static void Main(string[] args) {
        Vectors route = new Vectors();
        route.Add(new Vector(2.0, 90.0));
        route.Add(new Vector(1.0, 180.0));
        route.Add(new Vector(0.5, 45.0));
        route.Add(new Vector(2.5, 315.0));
        Console.WriteLine(route.Sum());
        Comparison<Vector> sorter = new Comparison<Vector>(VectorDelegates.rupare);
        route.Sort(sorter);
        Console.WriteLine(route.Sum());
        Predicate<Vector> searcher = new Predicate<Vector>(VectorDelegates.TopRightQuadrant);
        Vectors topRightQuadrantRoute = new Vectors(route.FindAll(searcher));
        Console.WriteLine(topRightQuadrantRoute.Sum());
    }
}