LINQ 笔记

       在LINQ开发当中var关键字显得特别的重要,当你声明一个var类型的变量时候,系统是不知道当前的类型,只有当你第一次为其赋值的时候,会根据其值来设置相应的数据类型,在LINQ查询通常不知道返回的类型,所以将查询到的结果放到var类型的变量当中 。

比如:

       Var myInt=0;//在编译的时候会自动将其转成int类型

       Var myBool=true;//编译的时候会将其转成bool类型

       Var myString=”ime,marcheson”//编译时自动将其转成string类型

class LowNums

{

    static void Main()

    {  

        // A simple data source.

        int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

 

        // Create the query.

        // lowNums is an IEnumerable<int>

        IEnumerable lowNums = from num in numbers

            where num < 5

            select num;

 

        // Execute the query.

        foreach (int i in lowNums)

        {

            Console.Write(i + " ");

        }

    }       

}

通过上面红色标记的那行就可以看出标准的LINQ语句通常包含from in where select这几个关键字,大家是不是感觉跟sql的语句很像,但是倘若你真拿SQL的语句来用一定会非常懊恼,因为他看似一样但实际上却是完全不同的两种标准,我们 将LINQ查询操作符,通过表格的形式列出来,如下。

查询操作符

含义

from 、in

用于定义任何LINQ表达式的主干,允许从合适的窗口中提取数据子集

where

用于定义从一个容器里取出哪些项的限制条件

select

用于从容器中选择一个序列

join、on、equals、into

基于指定的键来做关键操作。记住,这些“关联”不必与关系数据库的数据有关系

ordderby、ascending、descending

允许结果子集按升序和降序排序

group、by

用特定的值来对数据分组后得到一个子集

上面的通常 是创建一个查询,查询的结果为少于5的项,并且对其进行输出 。

在进行下面的知识之前一定要先了解IEnumerable和foreach这两个简单的概念。IEnumerable其实在C#是一个接口,在这个接口里面定义了一个方法GetEnumerator,这个方法的作用是返回一个循环访问集合的枚举器。这句话什么意义呢?就是当你的某一个对象继承于这个接口,那么这个对象就可以通过foreach来进行遍历,每次遍历就相当于调用GetEnumerator读取当前坐标的值并且定位到下一个坐标的位置。如我们常用的Array和list其实都是继承了这个接口的,那么只要定义这两个对象的时候选定相应的数据类型,并可以直接通过foreach来遍历组内的元素。

很多时候我们不知道返回的数据类型,那么最好的变法是将其定义成var类型,那么用户在通过foreach遍历的时候也将其改成var类型

class LowNums

{

    static void Main()

    {  

        // A simple data source.

        int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

 

        // Create the query.

        // lowNums is an IEnumerable<int>

        var lowNums = from num in numbers

            where num < 5

            select num;

 

        // Execute the query.

        foreach (var i in lowNums)

        {

            Console.Write(i + " ");

        }

    }       

}

Linq字句返回的是Enumerable对象,所以当你用LINQ查询的时候,可以在其外部调用Enumerable类的扩展方法。比如下面的查询可以通过调用ToArray<int>()和ToList<int>方法将查询到的结果,转换成相应类型的容器当中 。

int[] numbers = { 10, 20, 30, 40, 1, 2, 3, 8 };

            int[] subsetAsIntArray = (from i in numbers where i < 10 select i).ToArray<int>();

            List<int>subsetAsListOfInts=(from i in numbers where i<10 select i).ToList<int>();

Linq除了从简单的数组组里抽出结果以外,也可以操作System.Collections.Generic命名空间中的成员类型的数据,比如我们定义一个Car类。

public class Car

    {

        public string PetName { get; set; }

        public string Color { get; set; }

        public int Speed { get; set; }

        public string Make { get; set; }

}

紧接着我们在main函数里面,创建一个List集合,集合的类型为car.

  List<Car> myCars=new List<Car>(){

                new Car{PetName="Henry",Color="Silver",Speed=100,Make="BMW"},

                new Car{PetName="Daisy",Color="Tan",Speed=90,Make="BMW"},

                new Car{PetName="Mary",Color="Black",Speed=55,Make="VW"},

                new Car{PetName="Clunker",Color="Rust",Speed=5,Make="Yugo"},

                new Car{PetName="Melvin",Color="White",Speed=43,Make="Ford"}

            };

这里我们就可以通过linq对其进行操作,比如我们可以可以查询其Speed大于等于55小于等于100,并且Make为BMW的值,我们可以通过以下语句来查询;

var fastCars = from c in myCars where c.Speed >= 55 &&c.Speed<=100&& c.Make == "BMW" select c;

            foreach(var car in fastCars)

            {

                Console.WriteLine(car.PetName);

            }

这里我们发现对泛型容器的使用跟简单的数组没有什么区别,之前我们谈到泛型胡处理,那么是否非泛型的不能处理,答案当然不是,在C#里面提供一个ofType<T>()方法来将当前胡对象转化成一个一个兼容于IEnumerable<T>的对象。

static void LINQOverArrayList()

        {

            Console.WriteLine("***** LINQ over ArrayList*****");

            ArrayList myCars = new ArrayList()

            {

                new Car{PetName="Henry",Color="Silver",Speed=100,Make="BMW"},

                new Car{PetName="Daisy",Color="Tan",Speed=90,Make="BMW"},

                new Car{PetName="Mary",Color="Rust",Speed=55,Make="VW"}

            };

            var myCarsEnum=myCars.OfType<Car>();

 

            var fastCars = from c in myCarsEnum where c.Speed >= 55 select c;

            foreach(var car in fastCars)

            {

                Console.WriteLine("{0},is going to fast!", car.PetName);

            }

        }

对表达式进行排序

       查询表达式中我们通过orderby来对数据进行排序,排序默认按正序进行排序。你可以通过ascending操作符号来指定为正序排序,也可改为descending来进行逆序排序。

正序:

Var subset=from p in products orderby p.Name ascending select p;

逆序:

Var subset=from p in products orderby p.Name descending select p;

Enumerable还提供了一个扩展方法,可以对两个(或多个)LINQ查询的数据进行合并(union)比较(difference)、连接(concatenation)和交叉(intersection)。

Except()扩展方法,它返回含两个容器不同之处的LINQ集合集。下面的函数返回的只有一个”Yugo”

static void DisplayDiff()

        {

            List<string>myCars=new List<string>{"Yugo","Aztec","BMW"};

            List<string> yourCars = new List<string> { "BMW", "Saab", "Aztec" };

            var carDiff = (from c in myCars select c).Except(from c2 in yourCars select c2);

            Console.WriteLine("Here is what ou don't have,but I do:");

            foreach (string s in carDiff)

                Console.WriteLine(s);

        }

Intersect()方法返回两个容器中共同的数据项。将上面的程序修改一下,返回的将是”Aztec”、”BMW”

static void DisplayIntersection()

        {

            List<string> myCars = new List<string> { "Yugo", "Aztec", "BMW" };

            List<string> yourCars = new List<string> { "BMW", "Saab", "Aztec" };

            var carDiff = (from c in myCars select c).Intersect(from c2 in yourCars select c2);

            Console.WriteLine("Here is what ou don't have,but I do:");

            foreach (string s in carDiff)

                Console.WriteLine(s);

        }

Union()是将多个结果合并成一个,如果有相同的成员只返回一个结果。下面的程序返回的是Yugo、Aztec、BMW、Saab

static void DisplayUnion()

        {

            List<string> myCars = new List<string> { "Yugo", "Aztec", "BMW" };

            List<string> yourCars = new List<string> { "BMW", "Saab", "Aztec" };

            var carDiff = (from c in myCars select c).Union(from c2 in yourCars select c2);

            Console.WriteLine("Here is what ou don't have,but I do:");

            foreach (string s in carDiff)

                Console.WriteLine(s);

        }

Concat()是将所有的结果全部进行合并并且将其返回,如果出现重复的数据也照常返回。

原文地址:https://www.cnblogs.com/tianyake/p/3645052.html