Linq+lambda表达式+delegate委托详解及代码示例

一、Linq

简介:提供一种统一且对称的方式,让程序员在广义的数据上得到和操作“数据”。简单点说,就是在C#后台像sql查询一样操作集合和数组,从而筛选出我们想要的结果。

c#定义的各种简化查询
	代码示例:
   int[] scores1 = new int[] { 97, 92, 81, 60, 541, 1, 88, 81, 79 };
        int[] scores2 = new int[] { 97, 92, 81, 60, 541, 1, 88, 81, 79 };

        var scoreQuery = from score1 in scores1
                                      from score2 in scores2
                                      where score1 == score2 && score1 > 80
                                      orderby score1 descending
                                      select score1 + score2;

LinqToXml

代码示例:
using System.Xml.Linq;

   static void BuildXmlDocWithLINQToXml()
    {
        XDocument doc =new XDocument(
            new XDeclaration("1.0","utf-8","yes"),
            new XComment("Current Inventory of cars!"),
            new XProcessingInstruction("xml-stylesheet","href='MyStyle.css' title='compact' type='text/css'"),
                new XElement("Inventory",
                    new XElement("Car",new XAttribute("ID",1000),
                    new XElement("PetName","Jimbo"),
                    new XElement("Color","Red"),
                    new XElement("Make","Ford")
                        ),
                    new XElement("Car",new XAttribute("ID","I2"),
                    new XElement("PetName","Pink"),
                    new XElement("Color","Yugo"),
                    new XElement("Make","Melvin")
                        ) 
                    )
                );
        doc.Save("InventoryWithLinq.xml");
        doc.Descendants("PetName").Remove();
        Console.WriteLine(doc);
    }
    static void MakeXElementFromArray()
    {
        var people = new[] {
            new { FirstName="ss",Age=45} ,
            new { FirstName="撒大V",Age=43} ,
            new { FirstName="阿双方各",Age=65} ,
            new { FirstName="帷幄",Age=32} 
        };
        var arrays = from c in people
                     select
                         new XElement("Person", new XAttribute("Age", c.Age),
                         new XElement("FirstName", c.FirstName));
        XElement doc=new XElement("People",arrays);
        Console.WriteLine(doc);

        string myElement = @"<Car ID='3'>
                                 <Color>Yellow</Color>
                                 <Make>Yugo</Make>
                             </Car>";
        XElement newdoc = XElement.Parse(myElement);
        Console.WriteLine(doc);
        XElement doc2=XElement.Load("InventoryWithLinq.xml");
        //新增元素
        doc.Descendants("Person").First().Add(newdoc);
        //linq查询
        var makeInfo = from Car in doc2.Descendants("Car")
                       where (string)Car.Element("Color") == "Red"
                       select Car.Element("Color").Value;
    }

linq order by charindex 排序 按给定字符串顺序排序

//list=list.OrderBy(ee => SqlFunctions.CharIndex(“书记,主任,支部委员,村委委员,系统工作人员”, ee.ZhiWu)).ToList(); //linq to sql中报错:只能在linq to entities中调用此方法.
int i = 0;
list = list.OrderBy(ee => { i=Array.IndexOf(new string[] { “书记”, “主任”, “支部委员”, “村委委员”, “系统工作人员” }, ee.ZhiWu);if ( i!= -1) { return i; } else { return int.MaxValue; } }).ToList(); //字符串在字符数组中出现的位置,不在数组中的排在最后

扩展: 如果字符串是 村委委员1 那么就不在字符串数组中了会排到后面去(如上图),下面函数解决模糊匹配问题

int PatIndex(string[] array, string value)
        {
            int index = -1;
            for (int i = 0; i < array.Length; i++)
            {                
                //if (value.Contains(array[i]))
if (value.StartsWith(array[i]))//以搜索字符串开头的
                {
                    index = i;
                    break;
                }
            }
            return index;
        }
list = list.OrderBy(ee => { i=PatIndex(new string[] { "书记", "主任", "支部委员", "村委委员", "系统工作人员" }, ee.ZhiWu);if ( i!= -1) { return i; } else { return int.MaxValue; } }).ToList();

补充 sql:case when then
select * from table order by case when cunorju like ‘%街道%’ then 0 when cunorju like ‘%村委%’ then 1 when cunorju like ‘%居委%’ then 2 else 3 end
sql order by charindex(…):
Select * from table order by case when CharIndex(cunorju ,N’街道村委居委’)>0 then CharIndex(cunorju ,N’街道村委居委’) else 2000000000 end
/符合的放最前面,不符合的排在2000000000位置/

二、lambda表达式

简化版的匿名类

	代码示例:
	
	//Func == public delegate string Func(string func);

    public static void LambdaFun(string str,Func<string,string> func)
    {
        Console.WriteLine(func(str));
    }
	
	
	
	    List<string> Citys = new List<string>()
        {
           "BeiJing",
           "ShangHai",
           "Tianjin",
           "GuangDong"
        };
		
		//结合linq使用表达式
        var result = Citys.First(c => c.Length > 7);
        Console.WriteLine(result);

		//结合委托使用表达式
        LambdaFun("BeiJing 2013", s =>
        {
            if (s.Contains("2013"))
            {
                s = s.Replace("2013", "2018");
            }
            return s;
        });


		--------------利用lambda表达式计算算术树
		
        ParameterExpression a = Expression.Parameter(typeof(int), "i");
        ParameterExpression b = Expression.Parameter(typeof(int), "j");
        BinaryExpression r1 = Expression.Multiply(a, b);

        ParameterExpression c = Expression.Parameter(typeof(int), "w");
        ParameterExpression d = Expression.Parameter(typeof(int), "x");
        BinaryExpression r2 = Expression.Multiply(c, d);

        BinaryExpression result = Expression.Add(r1, r2);

        Expression<Func<int, int, int, int, int>> lambda = Expression.Lambda<Func<int, int, int, int, int>>(result, a, b, c, d);

        Console.WriteLine(lambda + "");

        Func<int, int, int, int, int> f = lambda.Compile();

        Console.WriteLine(f(1, 2, 1, 1) + "");
        Console.ReadKey();

三、delegate委托:

将方法作为参数传递(类似于C中的指针)

			代码示例:
			    public delegate void GreetingDelegate(string name);

				class DelegateTest
				{
					private static void EnglishGreeting(string name)
					{
						Console.WriteLine("Morning, " + name);
					}

					private static void ChineseGreeting(string name)
					{
						Console.WriteLine("早上好, " + name);
					}

					private static void EnglishGreetingNight(string name)
					{
						Console.WriteLine("Good Night, " + name);
					}

					//注意此方法,它接受一个GreetingDelegate类型的方法作为参数
					private static void GreetPeople(string name, GreetingDelegate MakeGreeting)
					{
						MakeGreeting(name);
					}

					static void Main(string[] args)
					{
						GreetPeople("Jimmy Zhang", EnglishGreeting);
						GreetPeople("张子阳", ChineseGreeting);

						GreetingDelegate del = new GreetingDelegate(EnglishGreeting);
						del += ChineseGreeting;
						GreetPeople("张子阳", del);

						del -= EnglishGreeting;
						del += EnglishGreetingNight;
						GreetPeople("Jimmy Zhang", del);

						GreetingDelegate del;
						del = ChineseGreeting;
						del += EnglishGreetingNight;

						del("hha");

						Console.ReadKey();
					}

				}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值