.NET Linq in C#

Posted zhaxichun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.NET Linq in C#相关的知识,希望对你有一定的参考价值。

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

namespace app
{

    /*
     Type Converter:    Enumerable.AsEnumerable
                        Queryable.AsQueryable
                        Enumerable / Queryable.Cast
                        Enumerable / Queryable.OfType
                        Enumerable.ToArray
                        Enumerable.ToDictionary
                        Enumerable.ToList
                        Enumerable.ToLookup  - to one-2-many dictionary
                        
     Elements:   ElementAt, 
                 ElementAtOrDefault, 
                 First, 
                 FirstOrDefault, 
                 Last,
                 LastOrDefault, 
                 Single, 
                 SingleOrDefault
                 
     Equal:      Enumerable / Queryable.SequenceEqual() - 通过以成对方式比较元素确定两个序列是否相等。
     
     Generator: - 生成是指创建新的值序列
                 Enumerable / Queryable.DefaultEmpty    - 用默认值单一实例集合替换空集合
                 Enumerable.Empty                       - 返回一个空集合
                 Enumerable.Range                       - 生成包含数字序列的集合
                 Enumerable.Repeat                      - 生成包含一个重复值的集合                                      
                           
     Group:    - 分组是指将数据分到不同的组,使每组中的元素拥有公共的属性。
     
                 Enumerable / Queryable.Groupby   - group...by.. | group...by...into...
                 Enumerable.ToLookup  - to one-2-many dictionary  - 将元素插入基于键选择器函数的 
                 
     Join:       Enumerable / Queryable.Join
                 Enumerable / Queryable.GroupJoin
                 
     PartitionData: - 将输入序列划分为两个部分的操作,无需重新排列元素,然后返回其中一个部分
                 Enumerable / Queryable.Skip
                 Enumerable / Queryable.SkipWhile        -基于谓词函数跳过元素,直到元素不符合条件
                 Enumerable / Queryable.Take
                 Enumerable / Queryable.TakeWhile        - 基于谓词函数获取元素,直到元素不符合条件
              
     Projection:    
        - 投影是指将对象转换为一种新形式的操作,该形式通常只包含那些将随后使用的属性。 
        - 通过使用投影,您可以构造从每个对象生成的新类型。 
        - 可以投影属性,并对该属性执行数学函数。 还可以在不更改原始对象的情况下投影该对象。
                 Enumerable / Queryable.Select
                 Enumerable / Queryable.SelectMany
                 
     Quantifier:  
        - 返回一个 Boolean 值,该值指示序列中是否有一些元素满足条件或是否所有元素都满足条件
                 Enumerable / Queryable.All
                 Enumerable / Queryable.Any
                 Enumerable / Queryable.Contains
                 
     Filtering: 
        - 结果集限制为仅包含满足指定条件的元素的操作。 它也称为选定内容
                 Enumerable / Queryable.OfType
                 Enumerable / Queryable.Where
                 u 
     
     Set Operation:
        - 集运算是指根据相同或不同集合(或集)中是否存在等效元素来生成结果集的查询运算
                 Enumerable / Queryable.Distinct     - 删除集合中的重复值。 
                 Enumerable / Queryable.Except       - 差集指位于一个集合但不位于另一个集合的元素。
                 Enumerable / Queryable.Intersect    - 交集指同时出现在两个集合中的元素
                 Enumerable / Queryable.Union        - 返回并集,并集指位于两个集合中任一集合的唯一的元素
                 
                 
     Others: Append, 
             Reverse,
             Then
             Zip         -  指定函数应用于两个序列的对应元素,以生成结果序列。
     * 
     */



    public class LinqDemo
    {
        List<int> list = new List<int>();

        public void TryLinq()
        {
            List<int> scores = new List<int>() { 80, 70, 90, 100 };

            IEnumerable<string> highScore = from score in scores
                                            where score > 80
                                            orderby score descending
                                            select $"The score is {score}";

            foreach (var item in highScore)
            {
                System.Console.WriteLine(item);
            }

            //=============================================================================================
            Country[] countries = { new Country(), new Country() };

            // to produce a sequence of groups organized by a key.
            var queryCountryGroup = from country in countries group country by country.Name;

            // select to generate a new type
            var queryNameAndPop = from country in countries
                                  select new { Name = country.Name, Pop = country.Population };


            // into - create a temporary identifier that stores a query.
            var percentQuery = from country in countries
                               let percentile = (int)country.Population / 10_000_000
                               group country by percentile into countryGroup
                               where countryGroup.Key >= 20
                               orderby countryGroup.Key
                               select countryGroup;

            // oderby - ascending or descending.
            var querySortedCountries = from country in countries
                                       orderby country.Name, country.Population descending
                                       select country;


            // join  - associate and/or combine elements from one data source with from others 

            // let - to store the result of an expression. such as a method call.

            string[] names = { "Omel DDD", "Claire ss", "Sven d", "Cesar s" };
            var queryNames = from name in names
                             let firstName = name.Split(‘ ‘)[0]
                             select firstName;

            // subquery
            Student[] students = { new Student(), new Student() };

            //- to to checked
            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()
                                };
        }

        // Aggregate - 
        public void AggregateDemo()
        {

        }

        // All [bool] - Determines whether all elements of a sequence satisfy a condition
        public bool All_Demo(string[] strs)
        {
            return strs.All((n) => n.StartsWith(‘a‘));
        }

        // Any [bool] - Determines whether a sequence contains any elements.
        public bool Any_Demo(string[] strs)
        {
            return strs.Any((n) => n.EndsWith(‘/‘));
        }


    }

    public class Country
    {
        public string City { get; set; }
        public string Name { get; set; }

        public int Population { get; set; }
    }
}




static void Main(string[] args)
{

    Student[] studentsInClassOne =
    {
                new Student(){Name = "AinOne", Age = 18, GradeLevel = 1},
                new Student(){Name = "BinOne", Age = 20, GradeLevel = 3},
                new Student(){Name = "CinOne", Age = 16, GradeLevel = 1},
                new Student(){Name = "DinOne", Age = 17, GradeLevel = 4},
                new Student(){Name = "EinOne", Age = 18, GradeLevel = 1}
            };

    Student[] studentsInClassTwo =
    {
                new Student(){Name = "AinTwo", Age = 18, GradeLevel = 1},
                new Student(){Name = "BinTwo", Age = 20, GradeLevel = 5},
                new Student(){Name = "CinTwo", Age = 18, GradeLevel = 1},
                new Student(){Name = "DinTwo", Age = 16, GradeLevel = 9},
                new Student(){Name = "EinTwo", Age = 17, GradeLevel = 4}
            };

    // all statement is to check the LINQ functions both in Linq expression and Method

    //Elements:  ElementAt(int index), First()
    //        Single() - 
    var stuOnElementsOperation = studentsInClassOne.ElementAt(1);
    var stuFirst = studentsInClassOne.First();

    Student singStudent = null;
    if (studentsInClassTwo.Length != 1)
    {
        singStudent = studentsInClassTwo.First();
    }
    else
    {
        singStudent = studentsInClassTwo.Single();
    }
    /*
    Console.WriteLine(stuOnElementsOperation.Name);
    Console.WriteLine(stuFirst.Name);
    Console.WriteLine(singStudent.Name);*/

    // Generator - create a new sequence base on that.=======================
    var range = Enumerable.Range(1, 150);
    var repeat = Enumerable.Repeat(21, 15);

    // Partition Data - Skip, SkipWhile, Take, TakeWhile=====================
    // SkipWhile() 
    // TakeWhile: loop each element, stop while false, return element have been looped that matched.
    var rangSkip = range.Skip(15);
    var rangeSkipWhile = range.SkipWhile(n => (n % 3 != 0));

    var rangeTake = range.Skip(15).Take(5);
    var rangeTakeWhile = range.Skip(9).TakeWhile(n => n > 10);

    string[] strList =
    {
                "One", "Two", "Three", "Five", "Six"
            };
    var resultList = strList.SkipWhile(s => s.Length < 4); //  "Three", "Five", "Six"


    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
    var numbersSkipWhile = numbers.SkipWhile(n => n % 3 != 0); // 3, 9, 8, 6, 7, 2, 0


    //==================================================================================
    // Quantifier - All, Any, Contains
    bool isAll = numbers.All(n => n % 3 == 0);
    bool isAny = numbers.Any(n => n % 3 == 0);
    bool isContains = numbers.Contains(8);
    bool isObject = studentsInClassOne.Contains(new Student() { Name = "EinOne", Age = 18, GradeLevel = 1 });
    Console.WriteLine("IsAll:{0}, IsAny:{1}, isObject:{2}", isAll, isAny, isObject);

    //==================================================================================
    // Filtering - OfType, Where
    var stuFilter = studentsInClassOne.Union(studentsInClassTwo).Where(n => n.GradeLevel == 12); // null, Not Execption throwed.
    foreach (var VARIABLE in stuFilter)
    {
        Console.WriteLine("Name:{0},Age:{1},GradeLevel:{2}", VARIABLE.Name, VARIABLE.Age, VARIABLE.GradeLevel);
    }

    //==================================================================================
    // Append, Reverse, Then, Zip
    var newnumbers = numbers.Append(100);
    int[] first = { 1, 2, 3, 4, 5 };
    int[] second = { 6, 7, 8, 9, 10 };
    var zipNumbers = first.Zip(second, (n, m) => n * m); // 6,14,36,50  Use Zip To preform.


    foreach (var number in zipNumbers)
    {
        Console.WriteLine(number);
    }
}

 

以上是关于.NET Linq in C#的主要内容,如果未能解决你的问题,请参考以下文章

错误 3002:映射片段中的问题 | c# linq 到实体

C# linq 多表in语句查询

c#编写的代码用:linq和传统的ado.net哪个好,出错少,哪个更快,对服务器的负担最小

C#中的LINQ

通过 ASP.NET MVC 在 C# 视图中遍历匿名对象的嵌套 LINQ 查询

.NET 中的 LINQ to JSON