Csharp/CSharp Tutorial/LINQ/Anonymous

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

Anonymous Method

using System;
using System.ruponentModel;
    class MainClass
    {
        static void Main()
        {
            Func<string, int> returnLength = delegate(string text) { return text.Length; };
            Console.WriteLine(returnLength("Hello"));
        }
    }

Anonymous Type

using System;
using System.ruponentModel;
    class MainClass
    {
        static void Main()
        {
            var tom = new { Name = "Tom", Age = 4 };
            var holly = new { Name = "Holly", Age = 31 };
            var jon = new { Name = "Jon", Age = 31 };
            Console.WriteLine("{0} is {1} years old", jon.Name, jon.Age);
        }
    }

Anonymous Type In Array

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ruponentModel;
    class AnonymousTypeInArray
    {
        static void Main()
        {
            var family = new[]                         
            {
                new { Name = "H", Age = 31 },      
                new { Name = "R", Age = 1 },       
                new { Name = "W", Age = 1 }      
            };
            int totalAge = 0;
            foreach (var person in family)
            {
                totalAge += person.Age;
            }
            Console.WriteLine("Total age: {0}", totalAge);
        }
    }

Anonymous Types

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ruponentModel;
    class AnonymousTypes
    {
        static void Main()
        {
            var jon = new { Name = "Jon", Age = 31 };
            var tom = new { Name = "Tom", Age = 4 };
            Console.WriteLine("{0} is {1}", jon.Name, jon.Age);
            Console.WriteLine("{0} is {1}", tom.Name, tom.Age);
        }
    }

Array of anonymous types

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        var curries = new[]
            {
                new { M = "A", S= "C", A = 5 },
                new { M = "B", S= "B", A= 5 },
                new { M = "C", S= "A", A= 5 }
            };
        Console.WriteLine(curries[0].ToString());
        Console.WriteLine(curries[0].GetHashCode());
        Console.WriteLine(curries[1].GetHashCode());
        Console.WriteLine(curries[2].GetHashCode());
        Console.WriteLine(curries[0].Equals(curries[1]));
        Console.WriteLine(curries[0].Equals(curries[2]));
        Console.WriteLine(curries[0] == curries[1]);
        Console.WriteLine(curries[0] == curries[2]);
    }
}

Construct instance for nested class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
    class Employee
    {
        public string Name { get; set; }
        public decimal Salary { get; set; }
    }
    class Department
    {
        public string Name { get; set; }
        List<Employee> employees = new List<Employee>();
        public IList<Employee> Employees
        {
            get { return employees; }
        }
    }
    class Company
    {
        public string Name { get; set; }
        List<Department> departments = new List<Department>();
        public IList<Department> Departments
        {
            get { return departments; }
        }
    }
    class SalaryReport
    {
        static void Main()
        {
            var company = new Company
            {
                Name = "A",
                Departments =
                {
                    new Department 
                    { 
                        Name = "Development", 
                        Employees = 
                        {
                            new Employee { Name = "T", Salary = 75000m },
                            new Employee { Name = "D", Salary = 45000m },
                            new Employee { Name = "M", Salary = 150000m }
                        }
                    },
                    new Department 
                    { 
                        Name = "Marketing", 
                        Employees = 
                        {
                            new Employee { Name = "Z", Salary = 200000m },
                            new Employee { Name = "X", Salary = 120000m }
                        }
                    }
                }
            };
            var query = company.Departments
                               .Select(dept => new { dept.Name, Cost = dept.Employees.Sum(person => person.Salary) })
                               .OrderByDescending(deptWithCost => deptWithCost.Cost);
            foreach (var item in query)
            {
                Console.WriteLine(item);
            }
        }
    }

Create new object from query

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
using System.Linq;
    class Car
    {
        public string PetName;
        public string Color;
        public int Speed;
        public string Make;
        
        public override string ToString()
        {
            return string.Format("Make={0}, Color={1}, Speed={2}, PetName={3}",Make, Color, Speed, PetName);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Car[] myCars = new []{
                new Car{ PetName = "A", Color = "Silver", Speed = 100, Make = "BMW"},
                new Car{ PetName = "B", Color = "Black", Speed = 55, Make = "VW"},
                new Car{ PetName = "C", Color = "White", Speed = 43, Make = "Ford"}
            };
        
            var makesColors = from c in myCars select new {c.Make, c.Color};
            foreach (var o in makesColors)
            {
                Console.WriteLine(o.ToString());
            }
        
        }
    }

Implicit Local Variables with Anonymous Types

class Program
{
  static void Main()
  {
      var patent1 =new { Title = "A",
                         YearOfPublication = "1984" };
      var patent2 =new { Title = "B",
                         YearOfPublication = "1977" };
      System.Console.WriteLine("{0} ({1})",patent1.Title, patent1.YearOfPublication);
      System.Console.WriteLine("{0} ({1})",patent2.Title, patent1.YearOfPublication);
  }
}

Return From Anonymous Method

using System;
using System.ruponentModel;
    class ReturnFromAnonymousMethod
    {
        static void Main()
        {
            Predicate<int> isEven = delegate(int x)
                { return x % 2 == 0; };
            Console.WriteLine(isEven(1));
            Console.WriteLine(isEven(4));
        }
    }

Simple Anonymous Methods for calculating the mean value

using System;
using System.Collections.Generic;
using System.ruponentModel;
    class MainClass
    {
        static void Main()
        {
            Action<IList<double>> printMean = delegate(IList<double> numbers)
                {
                    double total = 0;
                    foreach (double value in numbers)
                    {
                        total += value;
                    }
                    Console.WriteLine(total / numbers.Count);
                };
            double[] samples = { 1.5, 2.5, 3, 4.5 };
            printMean(samples);
        }
    }

Simple Anonymous Methods for printing out reverse numbers

using System;
using System.Collections.Generic;
using System.ruponentModel;
    class MainClass
    {
        static void Main()
        {
            Action<string> printReverse = delegate(string text)
                {
                    char[] chars = text.ToCharArray();
                    Array.Reverse(chars);
                    Console.WriteLine(new string(chars));
                };

            printReverse("Hello world");
        }
    }

Simple Anonymous Methods for printing the square root

using System;
using System.Collections.Generic;
using System.ruponentModel;
    class MainClass
    {
        static void Main()
        {
            Action<int> printRoot = delegate(int number)
                {
                    Console.WriteLine(Math.Sqrt(number));
                };

            printRoot(2);
        }
    }

Using Anonymous Methods with Find

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> myList1 = new List<string>();
            myList1.Add("A");
            myList1.Add("B");
            myList1.Add("C");
            myList1.Add("D");
            string vanilla1 = myList1.Find(delegate(string icecream)
            {
                return icecream.Equals("B");
            });
            Console.WriteLine(vanilla1);
        }
      
    }