为LINQ服务的C#新特性总结篇---扩展方法,匿名委托,lambda表达式,Action委托,Func委托,Linq中的order by,top和sum函数

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Diagnostics;

namespace ConsoleApplication1
{
    
static class Program
    {
        
static void Main(string[] args)
        {
            
//Predicate
            
//把方法当作参数传递
            DisplayProcess(Filter);
            
//匿名委托
            DisplayProcess(delegate(Process process) { return process.WorkingSet64 >= 20 * 1024 * 1024; });
            
//lambda表达式
            DisplayProcess(process =>  process.WorkingSet64 >= 20 * 1024 * 1024);


            
//action
            Action<string> print_string = (s) =>  Console.WriteLine(s);
            print_string.Invoke(
"就这么简单!");
            
//Func
            Func<DateTime> get_time = () => DateTime.Now;
            DateTime now 
= get_time.Invoke();
            print_string.Invoke(now.ToString());
            
//扩展方法
            List<int> int_list = new List<int> { 1234567 };
            
int b= int_list.list_sum();
            print_string.Invoke(b.ToString());
            
//sql中的top和order by
            var c = int_list.OrderByDescending(i => i).Take(3);
            
foreach (int k in c)
            {
                print_string.Invoke(k.ToString());
            }
            var d 
= int_list.OrderByDescending(i => i).Take(3).Sum();
            print_string.Invoke(d.ToString());

            Console.ReadKey();
        }
        
/// <summary>
        
/// 扩展方法必须在非泛型静态类中定义
        
/// </summary>
        
/// <param name="list"></param>
        
/// <returns></returns>
        static int list_sum(this IEnumerable<int> list)
        {
            
int a = 0;
            
foreach (var i in list)
            {
                a 
+= i;
            }
            
return a;
        }
        
/// <summary>
        
/// Predicate<Process>是泛型委托
        
/// 定义如下public delegate bool Predicate<T>(T obj);
        
/// </summary>
        
/// <param name="match"></param>
        private static void DisplayProcess(Predicate<Process> match)
        {
            
foreach(var process in Process.GetProcesses())
            {
                
if (match(process))
                {
                    Console.WriteLine(
"{0}            {1}", process.ProcessName, process.WorkingSet64);
                }
            }
            
        }
        
private static bool Filter(Process process)
        {
            
return process.WorkingSet64 >= 20 * 1024 * 1024;
        }
    }
}

posted @ 2009-10-18 11:48  liulun  阅读(1190)  评论(0编辑  收藏  举报