码迷,mamicode.com
首页 > Windows程序 > 详细

C#深度学习のLINQ

时间:2018-11-15 13:36:03      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:pre   any   name   条件   ssi   hover   galaxy   form   c99   

一、LINQ的由来

LINQ是Language Integrated Query的缩写,意思是语言扩展查询

查询是一种从数据源检索数据的表达式。 查询通常用专门的查询语言来表示。 随着时间的推移,人们已经为各种数据源开发了不同的语言;例如,用于关系数据库的 SQL 和用于 XML 的 XQuery。 因此,开发人员不得不针对他们必须支持的每种数据源或数据格式而学习新的查询语言。 LINQ 通过提供一种跨各种数据源和数据格式使用数据的一致模型,简化了这一情况。 在 LINQ 查询中,始终会用到对象。 可以使用相同的基本编码模式来查询和转换 XML 文档、SQL 数据库、ADO.NET 数据集、.NET 集合中的数据以及对其有 LINQ 提供程序可用的任何其他格式的数据。

二、LINQ的用法

一个linq应用的步骤主要有:

1、符合要求的数据源(可枚举,实现或者隐式实现IEnumerable的数据源)

2、构建查询语句

3、查询

下面是一个具体例子:

            //1、data source, 定义数据源
            int[] score = new int[5] 
            {
                1,
                23,
                67,
                9,
                22
            };
            // 2、numQuery is an IEnumerable<int> ,定义查询语句
            var numQuery =
                from num in score
                where (num % 2) == 0
                select num;

            //3、Query execution. 查询
            foreach (int num in numQuery)
            {
                Console.Write("{0,1} ", num);
            }

我们常见的foreach语句就是就是它的查询语句隐式

三、查询执行过程

linq查询我们foreach、.Count.Where.Any等是延迟执行的,也可以强制执行,需要用ToList,ToArry

List<int> numQuery2 =
    (from num in numbers
     where (num % 2) == 0
     select num).ToList();


var numQuery3 =
    (from num in numbers
     where (num % 2) == 0
     select num).ToArray();

四、常见示例

注:由于list和Arry等隐式实现IEnumerable接口,我们可以将对象放入其中来进行查询

1、多条件查询

            IEnumerable<int> numQuery =
                from num in score
                where (num % 2) == 0&&num < 20
                select num;

            foreach (int num in numQuery)
            {
                Console.Write("{0,1} ", num);
            }

2、结果排序

            IEnumerable<int> numQuery =
                from num in score
                where (num % 2) == 0&&num < 20
                orderby num ascending
                select num;

            foreach (int num in numQuery)
            {
                Console.Write("{0,1} ", num);
            }

3、let语句

var studentQuery6 =
    from student in students
    let totalScore = student.Scores[0] + student.Scores[1] +
        student.Scores[2] + student.Scores[3]
    select totalScore;

double averageScore = studentQuery6.Average();
Console.WriteLine("Class average score = {0}", averageScore);

4、group into

var studentQuery4 =
    from student in students
    group student by student.Last[0] into studentGroup
    orderby studentGroup.Key
    select studentGroup;

foreach (var groupOfStudents in studentQuery4)
{
    Console.WriteLine(groupOfStudents.Key);
    foreach (var student in groupOfStudents)
    {
        Console.WriteLine("   {0}, {1}",
            student.Last, student.First);
    }
}

5、select子句转换或投影

IEnumerable<string> studentQuery7 =
    from student in students
    where student.Last == "Garcia"
    select student.First;

6、构建对象,select相当于返回

var studentQuery8 =
    from student in students
    let x = student.Scores[0] + student.Scores[1] +
        student.Scores[2] + student.Scores[3]
    where x > averageScore
    select new { id = student.ID, score = x };

7、Join子句集合之间的连接,左连接,右连接。

var categoryQuery =
    from cat in categories
    join prod in products on cat equals prod.Category
    select new { Category = cat, Name = prod.Name };

8、子查询

var queryGroupMax =
    from student in students
    group student by student.GradeLevel into studentGroup
    select new
    {
        Level = studentGroup.Key,
        HighestScore =
            (from student2 in studentGroup
             select student2.Scores.Average())
             .Max()
    };

9、通过Take()和Skip()实现只显示部分查询结果。

                var qr = (from r in listStudents orderby r.score descending select r).Skip(i * pageSize).Take(5);

四、静态方法

System.Collections.Generic提供了一套 static (Shared 在 Visual Basic 中) 用于查询实现的对象方法 ,方便使用

主要有Aggregate、All、Any、Average、Contains、Count、Distinct、Except、First、GroupBy、GroupJoin、Join、Intersect、Last、Union、Where等

五、使用 yield 关键字,则指示在的方案、运算符或 get 访问器是迭代器。 使用的迭代器对集合的自定义迭代(语法糖)

    static void Main()
    {
        // Display powers of 2 up to the exponent of 8:
        foreach (int i in Power(2, 8))
        {
            Console.Write("{0} ", i);
        }
    }

    public static System.Collections.IEnumerable Power(int number, int exponent)
    {
        int result = 1;

        for (int i = 0; i < exponent; i++)
        {
            result = result * number;
            yield return result;
        }
    }
public static class GalaxyClass
{
    public static void ShowGalaxies()
    {
        var theGalaxies = new Galaxies();
        foreach (Galaxy theGalaxy in theGalaxies.NextGalaxy)
        {
            Debug.WriteLine(theGalaxy.Name + " " + theGalaxy.MegaLightYears.ToString());
        }
    }

    public class Galaxies
    {

        public System.Collections.Generic.IEnumerable<Galaxy> NextGalaxy
        {
            get
            {
                yield return new Galaxy { Name = "Tadpole", MegaLightYears = 400 };
                yield return new Galaxy { Name = "Pinwheel", MegaLightYears = 25 };
                yield return new Galaxy { Name = "Milky Way", MegaLightYears = 0 };
                yield return new Galaxy { Name = "Andromeda", MegaLightYears = 3 };
            }
        }

    }

    public class Galaxy
    {
        public String Name { get; set; }
        public int MegaLightYears { get; set; }
    }
}

 

C#深度学习のLINQ

标签:pre   any   name   条件   ssi   hover   galaxy   form   c99   

原文地址:https://www.cnblogs.com/xietianjiao/p/9962642.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!