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

本文通过具体的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;
        }
    }
}

转载于:https://www.cnblogs.com/pangxiaoliang/archive/2009/07/28/1530654.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值