一颗不安分的创业心

C#细节之lambda,linq,匿名方法

看代码,得永生
不再解释,很容易的,我没有仔细研究过,在此记下,以后深入研究。
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;

namespace Landpy
{
    
class Starter
    {
        
delegate int Add(int i, int j);
        
delegate bool Compare(int i, int j);
        
delegate void NoNameMethod(string name);
        
static void Main()
        {
            Add add 
= (x, y) => x + y;
            Console.WriteLine(add.Invoke(
12));
            Compare compare 
= (i, j) => i == j;
            Console.WriteLine(compare.Invoke(
12));
            Console.WriteLine(compare.Invoke(
11));
            NoNameMethod noNameMethod 
=
                
delegate(string name)
                {
                    Console.WriteLine(String.Format(
"Hello {0}!", name));
                };
            Action
<int> hello = delegate(int i)
            {
                
for (int j = 0; j < i; j++)
                {
                    Console.WriteLine(
"Hello");
                }
            };
            noNameMethod.Invoke(
"Landpy");
            hello.Invoke(
3);

            
string[] names = { "++landpy""pxl""ljc""baby" };
            
//lambda的写法 
            var quereynamestwo = names.Where(n => n.Length == 3).Select(n => n.Substring(2));//.Select(n => n.Name);

            
//linq的写法 
            var quereynames = from n in names
                              
where n.Length == 3
                              select n;

            
foreach (string name in quereynames)
            {
                Console.WriteLine(name);
            }

            
foreach (string name in quereynamestwo)
            {
                Console.WriteLine(name);
            }

            ArrayList employees 
= new ArrayList();

            
for (int i = 0; i < 10; i++)
            {
                Employee employee 
= new Employee();
                employee.Name 
= "Name" + i.ToString();
                employee.Age 
= i;
                employees.Add(employee);
            }

            Employee[] employeesArray 
= (Employee[])employees.ToArray(typeof(Employee));

            var es 
= employeesArray.Where(n => n.Age > 4);
            
foreach (Employee employeeTmp in es)
            {
                Console.WriteLine(employeeTmp.Name);
            }
        }
    }

    
class Employee
    {
        
public string Name
        {
            
get;
            
set;
        }

        
public int Age
        {
            
get;
            
set;
        }
    }
}
posted @ 2009-07-28 15:23  pangxiaoliang[北京]流浪者  阅读(554)  评论(0编辑  收藏  举报
小豆芽之父