您的位置:首页 > 其它

linq用法

2015-08-04 12:03 302 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: