Linq Quick Reference

简介:

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

namespace LinqQuickReference
{
    class Program
    {
        static void Main(string[] args)
        {   
            //######linq to object#######
            #region ######linq to object#######
            Console.WriteLine();
            Console.WriteLine("######linq to object#######");
            int[] array = { 1, 2, 4, 3, 6, 5, 4, 3, 6, 7, 5, 0, 5 };

            //遍历
            Console.WriteLine("//遍历");
            var result = from e in array
                         select e;
            foreach (var item in result)
            {
                Console.Write("{0} ", item.ToString());
            }


            //遍历时候可以强制转换类型 
            //建议指定本地变量,容易引起报错
            Console.WriteLine();
            Console.WriteLine("//遍历时候可以强制转换类型");
            Console.WriteLine("//建议指定本地变量,容易引起报错");
            var result1 = from object e in array
                          select e;
            foreach (var item in result1)
            {
                Console.Write("{0} ", item.ToString());
            }

 

            student[] s ={new student(1,"zhangsan",true,100),
                             new student(2,"lisi",true,90),
                             new student(3,"wangwu",false,80),
                             new student(4,"zhaoliu",true,90),
                             new student(5,"tom",false,20),

                        };

            //遍历 select e
            Console.WriteLine();
            Console.WriteLine("//遍历 select e");
            var result2 = from e in s
                          select e;
            foreach (var item in result2)
            {
                Console.Write("{0} ", item._name);
            }


            //遍历 select e._name 
            Console.WriteLine();
            Console.WriteLine("//遍历 select e._name ");
            var result3 = from e in s
                          select e._name;
            foreach (var item in result3)
            {
                Console.Write("{0} ", item);
                Console.Write("{0} ", item.GetType());
            }
            Console.Write("{0} ", result3.GetType());

            //遍历 select 匿名类型
            Console.WriteLine();
            Console.WriteLine("//遍历 select 匿名类型");
            var result4 = from e in s
                          select new { val1 = e._id.ToString() + "-" + e._name, e._score, val3 = e._sex.ToString() + "&" + e._name };
            foreach (var item in result4)
            {
                Console.Write("{0} ", item);
            }
            Console.WriteLine();

            foreach (var item in result4)
            {
                Console.Write("{0} ", item.val3);
            }


            //遍历 + where
            Console.WriteLine();
            Console.WriteLine("//遍历 + where");
            var result5 = from e in array
                          where e > 5
                          select e;
            foreach (var item in result5)
            {
                Console.Write("{0} ", item);
            }

            Console.WriteLine();
            var result6 = from e in s
                          where e._score < 90
                          select e;
            foreach (var item in result6)
            {
                Console.Write("{0} ", item._name);
            }

            //遍历 + order by
            Console.WriteLine();
            Console.WriteLine("//遍历 + order by");
            var result7 = from e in array
                          where e > 5
                          orderby e descending
                          select e;
            foreach (var item in result7)
            {
                Console.Write("{0} ", item);
            }

            Console.WriteLine();
            var result8 = from e in s
                          where e._score < 90
                          orderby e._score ascending
                          select e;
            foreach (var item in result8)
            {
                Console.Write("{0} ", item._name);
            }

            //linq 对象查询方法 --使用Lambda表达式 --where方法
            Console.WriteLine();
            Console.WriteLine("//linq 对象查询方法--使用Lambda表达式 --where方法");

            //var result9 = from e in array
            //              select e;
            //result9= result9.Where(v => v > 3);

            //或者可以连起来写
            var result9 = (from e in array
                           select e).Where((v, theindex) => v > 3 || theindex < 2);

            foreach (var item in result9)
            {
                Console.Write("{0} ", item);
            }

            //linq 对象查询方法 --使用Lambda表达式 --orderby方法
            Console.WriteLine();
            Console.WriteLine("//linq 对象查询方法--使用Lambda表达式 --orderby方法");

            var result10 = (from e in array
                            select e).OrderBy(v => v % 3);//根据元素的对3求余的结果排序

            foreach (var item in result10)
            {
                Console.Write("{0} ", item);
            }

            //linq 对象查询方法 --使用Lambda表达式 --skip方法 skipwhile方法
            Console.WriteLine();
            Console.WriteLine("//linq 对象查询方法--使用Lambda表达式 --skip方法 skipwhile方法");

            var result11 = (from e in array
                            select e).Skip(3);//跳过前面3个

            foreach (var item in result11)
            {
                Console.Write("{0} ", item);
            }

            Console.WriteLine();
            var result12 = (from e in array
                            select e).SkipWhile(v => v % 3 > 0);//跳过v%3>0的元素,一旦不满足该条件,停止跳过,语句结束。

            foreach (var item in result12)
            {
                Console.Write("{0} ", item);
            }

            //linq 对象查询方法 --使用Lambda表达式 --take方法 takewhile方法
            //和skip,skipwhile正好相反,取元素
            Console.WriteLine();
            Console.WriteLine("//linq 对象查询方法--使用Lambda表达式 --skip方法 takewhile方法");
            Console.WriteLine("//和skip,skipwhile正好相反,取元素");

            var result13 = (from e in array
                            select e).Take(3);//取前面3个

            foreach (var item in result13)
            {
                Console.Write("{0} ", item);
            }

            Console.WriteLine();
            var result14 = (from e in array
                            select e).TakeWhile(v => v % 3 < 2);//取v%3>0的元素,一旦不满足该条件,停止跳过,语句结束。

            foreach (var item in result14)
            {
                Console.Write("{0} ", item);
            }

            //linq 对象查询方法 --使用Lambda表达式 --select方法
            Console.WriteLine();
            Console.WriteLine("//linq 对象查询方法 --使用Lambda表达式 --select方法");

            var result15 = (from e in array
                            select e).Select(v => v > 5);

            foreach (var item in result15)
            {
                Console.Write("{0} ", item);
            }


            //linq 对象查询方法 --使用Lambda表达式 --max方法
            Console.WriteLine();
            Console.WriteLine("//linq 对象查询方法 --使用Lambda表达式 --max,sum,average方法");

            var result16 = (from e in s
                            select e._score);

            Console.WriteLine("result16.Max() {0} ", result16.Max());//resule:100;
            Console.WriteLine(" result16.Max(v=>v<100) {0} ", result16.Max(v=>v<100)); //result:true
            Console.WriteLine("result16.Sum() {0} ", result16.Sum());
            Console.WriteLine("result16.Sum(v=>v%3) {0} ", result16.Sum(v=>v%3));
            Console.WriteLine("result16.Average() {0} ", result16.Average());
            Console.WriteLine("result16.Average(v => v % 4) {0} ", result16.Average(v => v % 4));


            //linq 对象查询方法 --使用Lambda表达式 --Distinct方法
            Console.WriteLine();
            Console.WriteLine("//linq 对象查询方法 --使用Lambda表达式 --Distinct方法");

            var result17 = (from e in array
                            select e).Distinct();

            foreach (var item in result17)
            {
                Console.Write("{0} ", item);
            }


            //linq 对象查询方法 --使用Lambda表达式 --Count方法
            Console.WriteLine();
            Console.WriteLine("//linq 对象查询方法 --使用Lambda表达式 --Distinct方法");

            var result18 = (from e in array
                            select e).Count();
            Console.Write ("{0} ", result18);
            Console.WriteLine("{0} ", result18.GetType().ToString());

            //linq 对象查询方法 --使用Lambda表达式 --contains方法
            Console.WriteLine();
            Console.WriteLine("//linq 对象查询方法  --Contains方法 判断是否包含特定元素");

            var result19 = (from e in array
                            select e).Contains(3);
            
            Console.Write ("{0} ", result19);
            Console.WriteLine("{0} ", result19.GetType().ToString());

            var result20 = (from e in s
                            select e._name).Contains("zhangsan");

            Console.Write("{0} ", result20);
            Console.WriteLine("{0} ", result20.GetType().ToString());
            #endregion

            //######linq to dataset#######
            #region ######linq to dataset#######
            Console.WriteLine();
            Console.WriteLine("######linq to dataset#######");
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[]
                {
                    new DataColumn("no",Type.GetType("System.Int32")),
                    new DataColumn("name",Type.GetType("System.String")),
                    new DataColumn("age",Type.GetType("System.Int32")),
                    new DataColumn("score",Type.GetType("System.Int32")),
                }
                );

            DataTable dtmoney = new DataTable();
            dtmoney.Columns.AddRange(new DataColumn[]
                {
                    new DataColumn("no",Type.GetType("System.Int32")),
                    new DataColumn("money",Type.GetType("System.Decimal")),
                }
                );

            int[] nolist = { 1,2,3,4,5};
            string[] namelist = {"zhang","wang","qian","li","sun" };
            int[] age = { 20,21,19,22,20};
            int[] score = { 100,90,80,80,70};
            Decimal [] moneylist = { 400.23m, 324.32m, 303.42m,230m,399.1m };

            for (int i = 0; i < 5; i++)
            {
                DataRow dr = dt.NewRow();
                dr["no"] = nolist[i];
                dr["name"] = namelist[i];
                dr["age"] = age[i];
                dr["score"] = score[i];
                dt.Rows.Add(dr);


                DataRow drmoney = dtmoney.NewRow();
                drmoney["no"] = nolist[i];
                drmoney["money"] = moneylist[i];
                dtmoney.Rows.Add(drmoney);

            }

 

            //遍历 linq to dataset
            Console.WriteLine();
            Console.WriteLine("######linq to dataset#######");
            var result50 = from e in dt.AsEnumerable()
                           select e;
            foreach (var item in result50)
            {
                Console.Write("{0} ", item.Field<string>("name"));
            }


            //遍历 linq to dataset
            Console.WriteLine();
            Console.WriteLine("//遍历 linq to dataset");
            var result51 = from e in dt.AsEnumerable()
                           where e.Field<string>("name").Contains("a")
                           select e;
            foreach (var item in result51)
            {
                Console.Write("{0} ", item.Field<string>("name"));
            }

            //遍历 where
            Console.WriteLine();
            Console.WriteLine("//遍历 where");
            var result52 = from e in dt.AsEnumerable()
                           where e.Field<string>("name")=="zhang"
                           select e.Field<int>("score");
            foreach (var item in result52)
            {
                Console.Write("{0} ", item);
            }

            //遍历 order
            Console.WriteLine();
            Console.WriteLine("//遍历 order");
            var result53 = from e in dt.AsEnumerable()
                           orderby e.Field<int>("score")
                           select e;
            foreach (var item in result53)
            {
                Console.Write("{0} ", item.Field<string>("name"));
            }


            
            //遍历 两个table
            Console.WriteLine();
            Console.WriteLine("//遍历 两个table where-子句");
            var result54 = from e in dt.AsEnumerable()
                           from e1 in dtmoney.AsEnumerable()
                           where e1.Field<int>("no")==e.Field<int>("no")
                           orderby e1.Field<decimal>("money")
                           select new {val=e.Field<string>("name")+"-" +e1.Field<decimal>("money").ToString()};
            foreach (var item in result54)
            {
                Console.Write("{0} ", item.val);
            }

            //遍历 两个table -join子句
            //var result55 = from e in dt.AsEnumerable()
            //               join e1 in dtmoney.AsEnumerable()
            //               on e.Field<int>("no") equals e1.Field<int>("no")
            //               orderby e1.Field<decimal>("money")
            //               select new { val = e.Field<string>("name") + "-" + e1.Field<decimal>("money").ToString() };
            Console.WriteLine();
            Console.WriteLine("//遍历 两个table -join子句");
            Console.WriteLine("//var result55 = from e in dt.AsEnumerable()");
            Console.WriteLine("//               join e1 in dtmoney.AsEnumerable()");
            Console.WriteLine("//               on e.Field<int>(\"no\") equals e1.Field<int>(\"no\")//e和e1的顺序不能对调,equals 而不是==");
            Console.WriteLine("//               orderby e1.Field<decimal>(\"money\")");
            Console.WriteLine("//               select new { val = e.Field<string>(\"name\") + \"-\" + e1.Field<decimal>(\"money\").ToString() };");
            var result55 = from e in dt.AsEnumerable()
                           join e1 in dtmoney.AsEnumerable()
                           on e.Field<int>("no") equals e1.Field<int>("no") //e和e1的顺序不能对调,equals 而不是==
                           orderby e1.Field<decimal>("money")
                           select new { val = e.Field<string>("name") + "-" + e1.Field<decimal>("money").ToString() };
            foreach (var item in result55)
            {
                Console.Write("{0} ", item.val);
            }


            //遍历 两个table -join子句 分组连接
            //var result55 = from e in dt.AsEnumerable()
            //               join e1 in dtmoney.AsEnumerable()
            //               on e.Field<int>("no") equals e1.Field<int>("no")
            //               orderby e1.Field<decimal>("money")
            //               select new { val = e.Field<string>("name") + "-" + e1.Field<decimal>("money").ToString() };
            Console.WriteLine();

            var result56 = from e in dt.AsEnumerable()
                           join e1 in dtmoney.AsEnumerable()
                           on e.Field<int>("no") equals e1.Field<int>("no") //e和e1的顺序不能对调,equals 而不是==
                           into tmpresult
                           from e2 in tmpresult  //tmpresult的类型变为一个datarow的数组
                           select e2;
            foreach (var item in result56)
            {
                Console.Write("{0} ", item.Table.Columns[0].ColumnName);
                Console.Write("{0} ", item["no"]);
            }

 

 


            //遍历 两个table -join方法
            //var result55 = from e in dt.AsEnumerable()
            //               join e1 in dtmoney.AsEnumerable()
            //               on e.Field<int>("no") equals e1.Field<int>("no")
            //               orderby e1.Field<decimal>("money")
            //               select new { val = e.Field<string>("name") + "-" + e1.Field<decimal>("money").ToString() };
            Console.WriteLine();
            Console.WriteLine("//遍历 两个table -join方法");
            var result57 = (from e in dt.AsEnumerable()
                            select e).Join(dtmoney.AsEnumerable(), v1 => v1["no"], v2 => v2["no"]+"ddd", (v1, v2) => new { result=v1["no"],result1=v2["money"]});
            //join方法参数参考
            //http://msdn.microsoft.com/en-us/library/bb534644.aspx
            foreach (var item in result57)
            {
                Console.Write("{0} ", item);
            }

 

 

            #endregion

        }

 

        class student
        {
            public int _id;
            public string _name;
            public bool _sex;
            public int _score;

            public student(int id, string name, bool sex, int score)
            {
                _id = id;
                _name = name;
                _sex = sex;
                _score = score;
            }

        }
    }
}
 

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

判断结果集是否包含某些特定项

            var menurole = (from el in dtroles.AsEnumerable()

                            select new { menuid = el.Field<int>("menuid"), canread = el.Field<bool>("canread") }

                            ).Distinct();

menurole.Contains(new { menuid = 4, canread = true }) //判断是否包含

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
取前几项

var pagerole = (from el in dtroles.AsEnumerable() //get page permission

                            where el.Field<string>("page") == page

                            select el).Take(1);

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

直接读取指定的元素,不使用foreach遍历

canread = pagerole.ElementAt(0).Field<bool>("canread");

















本文转自cnn23711151CTO博客,原文链接:http://blog.51cto.com/cnn237111/472404,如需转载请自行联系原作者



相关文章
|
3月前
|
SQL 开发框架 .NET
聊聊 System.Linq.Dynamic,以及分享一个使用 System.Linq.Dynamic 扩展 LINQ 查询的详细例子
聊聊 System.Linq.Dynamic,以及分享一个使用 System.Linq.Dynamic 扩展 LINQ 查询的详细例子
102 0
|
开发框架 .NET C#
【C#】Language_Integrated_Query——LINQ
欢迎来到本篇LINQ教程,本文介绍了如何使用C#中的LINQ(Language Integrated Query)。LINQ是C#中的功能,可用于从集合中检索,过滤和操作数据。
|
.NET 开发框架 数据库
深入调研Linq to Objects Join Linq to Entity
最近工作中遇到数据库组合查询带来的一些问题,因此有必要调研一下Linq to Objects Join Linq to Entity。参考一些网友的代码案例,深入实践了一下使用EntityFramework Code First 下的组合查询。
1249 0