linq用法

1.什么是linq

  这个就不解释了~~

  两种查找方法:查询表达式和方法语法


查询表达式关键字:Where、Select、SelectMany、OrderBy、ThenBy、OrderByDescending、ThenByDescending、GroupBy、Join、GroupJoin

查询表达式语法:

from [type] id in source

[join [type] id in source on expr equals expr [into subGroup]]

[ from [type] id in source | let id = expr | where condition]

[ orderby ordering,ordering,ordering...]

select expr | group expr by key

[into id query]



2.使用linq 的两个步骤

    创建查询形式

    执行查询

3. 注意点

   所有的linq查询都是以from 开始  以select 或者group 结束

   查询形式确定后 改变查询的数据原 结果随之改变



4.  简单例子

             int[] arr = { 1, 2, -3, -4, 5, 6, 7, 8 };

            var posNums = from num in arr   // num: 范围变量
                          where num > 0  // 查询条件 (推断)  必须是bool 值  过滤数据
                          select num;                                             -----------------------> 创建查询形式


            StringBuilder sb = new StringBuilder();
            foreach (var item in posNums)                        -------------------------> 执行查询
            {
                sb.AppendFormat("{0},", item);
            }
            MessageBox.Show(sb.ToString());


5. 知识点

      可以返回对范围变量的操作结果

  var posNums = from num in arr  
                          where num > 0 
                          select num*2;        


可以在中间定义一个变量

var posNums = from num in arr  

  let index = 2  //定义一个变量
                          where num > 0 
                          select num*index ;   



分组:



              string[] arr = { ".net", "www.baidu.com", "www.google.com", "www.bing.com", "ee" };


            var aa = from a in arr
                     let index = a.LastIndexOf(".") // 可以在中间定义一个变量
                     where index != -1
                     group a by a.Substring(index);

           foreach (var item in aa) // 遍历组
            {
                StringBuilder sb = new StringBuilder();
                sb.Length = 0;


                sb.AppendFormat("{0}:", item.Key);
                sb.AppendLine();
                foreach (var i in item) // 遍历组中的元素
                {
                    sb.AppendFormat("{0},", i);
                }
               
                MessageBox.Show(sb.ToString());   
            }
            


操作符使用示例:

        http://www.aizhengli.com/yubinfeng-net-mianxiangduixiangjichu/776/LINQ%E4%BD%BF%E7%94%A8.html



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值