浅谈Linq查询

一.Var关键字

在学习Linq查询之前,我们先来学习var关键字的用法,看看微软官方的定义:从Visual C#3.0开始,在方法范围声明的变量可以具有隐式“类型” var隐式类型的局部变量是强类型的,就像您自己声明了类型一样,但编译器确定了类型。从这个定义我们有两点需要注意,首先用var申明的隐式类型的局部变量是强类型的,二.var的推断类型是在编译的时候确定的,不是在运行的时候。

再看看微软官方给出的两个例子:

// Example #1: var is optional when
// the select clause specifies a string
string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
var wordQuery = from word in words
                where word[0] == 'g'
                select word;

// Because each element in the sequence is a string, 
// not an anonymous type, var is optional here also.
foreach (string s in wordQuery)
{
    Console.WriteLine(s);
}

var允许使用但不是必需的,因为查询结果的类型可以明确地表示为IEnumerable<string>

// Example #2: var is required because
// the select clause specifies an anonymous type
var custQuery = from cust in customers
                where cust.City == "Phoenix"
                select new { cust.Name, cust.Phone };

// var must be used because each item 
// in the sequence is an anonymous type
foreach (var item in custQuery)
{
    Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);
}

var允许结果是匿名类型的集合,除了编译器本身之外,不能访问该类型的名称。使用var消除了为结果创建新类的要求

 在第二个例子中假如不用var关键字的话我们就要事先创建好类,查询条件一变,查询结果就跟着改变,又要定义新的类型,linq查询的条件是随意变化的,不可能条件一变就声明新的类型,所以var关键字对linq查询至关重要的。

二.匿名类

 创建一个对象一定要先定义这个对象的类型么,当然不是,我们可以通过匿名类的方式来创建对象,看看下面这段代码:

  static void Main(string[] args)
        {
            string name = "Tom";
            int age = 20;
            var obj = new { name,age };
            Console.WriteLine(obj.age.ToString() + obj.name.ToString());
            Console.Read();

        }

三.Linq查询

Linq查询实质是操作集合的一系列扩展方法,Linq特性的核心接口是IEnumerable,只有实现了IEnumerable接口的集合才可以用Linq查询。

Linq的查询包含三种方法:

1.使用语法查询,这种查询方式和SQL语句比较像:

// Query #1.
            List<int> objInt = new List<int> { 1, 2, 5, 4, 3, 9, 7, 6, 11, 29, 99 };
            var result = from i in objInt
                         where i > 3 && i < 20
                         orderby i descending
                         select i;

            foreach (var item in result)
            {
                Console.WriteLine(item.ToString());
            }

            Console.Read();

            // Query #2.
            List<string> objListString = new List<string> { "abc", "acd", "bcv", "bcd", "cnh", "ckl", "glk" };
            var strResult = from str in objListString
                            group str by str[0];
            foreach (var item in strResult)
            {
                foreach (var item1 in item)
                {
                    Console.WriteLine(item1);
                }
            }

            Console.Read();

        }

2.使用扩展方法查询:

某些方法查询必须表现为方法调用,最常见的此类方法是可返回单一数值的方法,例如 SumMaxMinAverage 等。 这些方法在任何查询中都必须始终最后一个调用,因为它们只表示单个值,不能用作其他查询操作的源。

扩展方法select的使用:

 static void Main(string[] args)
        {
            int[] nums = { 1, 7, 2, 6, 5, 4, 9, 13, 20 };

            var list = nums.Select(item => item * item);
            foreach (int item in list)
            {
                Console.WriteLine(item);
            }

            Console.ReadLine();
        }

扩展方法Where的使用:

  static void Main(string[] args)
        {
            int[] nums = { 1, 7, 2, 6, 5, 4, 9, 13, 20 };

            var list = nums
                .Where(item => item % 2 == 0)
                .Select(i => i * i);

            Console.ReadLine();
        }

扩展方法orderby的用法:

        static void Main(string[] args)
        {
            int[] nums = { 1, 7, 2, 6, 5, 4, 9, 13, 20 };
            var list = nums
                .Where(item => item % 2 == 0)
                .Select(i => i * i)
                .OrderBy(item => item);
            foreach (int i in list)
            {
                Console.WriteLine(i);
            }

            Console.ReadLine();
        }

static void Main(string[] args)
{
string[] nums = { "张勇", "王琦", "刘静", "赵鑫鑫",
"杜丽", "马俊才", "那英", "成龙", };


var list = nums
.Where(item => item.Length == 2)
.Select(item => item)
.OrderByDescending(item => item.Substring(0, 1));
foreach (string item in list)
{
Console.WriteLine(item);
}


Console.ReadLine();
}

3.结合使用查询语法和方法语法:

int numCount1 =
    (from num in numbers1
     where num < 3 || num > 7
     select num).Count();

由于查询 返回单个值而不是集合,因此查询立即执行

 

posted @ 2019-06-26 17:20  大艺术家007  阅读(530)  评论(0编辑  收藏  举报