C# Linq Detailed Explanation 3

Table of contents

overview

Thirteen, Sum/Min/Max/Average

14. Distinct

15. Concat

16. Join

Seventeen, ToList 

Eighteen, ToArray

Nineteen, ToDictionary


C# Linq Detailed Explanation
1.Where
2.Select
3.GroupBy
4.First / FirstOrDefault
5.Last / LastOrDefault

C# Linq Detailed Explanation 2
1.OrderBy 
2.OrderByDescending
3.Skip
4.Take
5.Any
6.All

C# Linq Detailed Explanation 3
1.Sum / Min / Max / Average
2.Distinct
3.Concat
4.Join
5.ToList 
6.ToArray
7.ToDictionary

C# Linq 详解四
1.SelectMany
2.Aggregate
3.DistinctBy
4.Reverse
5.SequenceEqual
6.Zip
7.SkipWhile 
8.TakeWhile

C# Linq Detailed Explanation 1 - Xiong Siyu's Blog - CSDN Blog

C# Linq Detailed Explanation II - Xiong Siyu's Blog - CSDN Blog

C# Linq Detailed Explanation 4 - Xiong Siyu's Blog - CSDN Blog

overview

Language-Integrated Query (LINQ) is a collection of technologies that directly integrate query functionality into the C# language. Data queries have historically been expressed as simple strings, with no compile-time type checking or IntelliSense support. In addition, you need to know a different query language for each type of data source: SQL databases, XML documents, various Web services, and so on. With LINQ, queries are the highest-level language constructs, just like classes, methods, and events.

For developers writing queries, the most obvious "language integration" part of LINQ is query expressions. Query expressions are written using declarative query syntax. Using query syntax, you can perform filtering, sorting, and grouping operations on data sources with minimal code. The same basic query expression patterns can be used to query and transform data in SQL databases, ADO .NET datasets, XML documents and streams, and .NET collections.
 

Thirteen, Sum/Min/Max/Average

Computes the sum, minimum, maximum, and average of specified attributes in a sequence.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            List<int> numList = new List<int> { 1, 4, 5, 24, 43, 67, 12, 90, 15 };
            int sum = numList.Sum();
            Console.WriteLine("总和:{0}", sum);

            int min = numList.Min();
            Console.WriteLine("最小值:{0}", min);

            int max = numList.Max();
            Console.WriteLine("最大值:{0}", max);

            double average = numList.Average();
            Console.WriteLine("平均值:{0}", average);

            Console.ReadKey();
        }
    }
}

run:

14. Distinct

The Distinct method is used to filter out unique elements from a collection. It returns a new collection containing the unique elements from the original collection.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int[] numList = { 1, 2, 2, 3, 3, 4, 5, 5 };
            var distinctNumbers = numList.Distinct();
            foreach (var number in distinctNumbers)
            {
                Console.WriteLine(number);
            }

            Console.ReadKey();
        }
    }
}

run:

15. Concat

The Concat method is used to merge two collections into a new collection. The current method does not have an overloaded function. It is usually used to sort the array, pick out the required collection, and reprocess after merging.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int[] numbers1 = { 1, 2, 3 };
            int[] numbers2 = { 4, 5, 6 };
            var mergedNumbers = numbers1.Concat(numbers2);
            foreach (var number in mergedNumbers)
            {
                Console.WriteLine(number);
            }

            Console.ReadKey();
        }
    }
}

run:

16. Join

Matches the elements of two sequences according to their associated keys.

The usage of Join is relatively complicated in Linq, and there are many changes when using it. Here is a simple example. It is recommended that you write more and practice more, and write more cases. You will be more familiar with it if you use it more.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            List<Student> students1 = new List<Student>
            {
                new Student { Id = 1, Name = "柱子" },
                new Student { Id = 2, Name = "李四" },
                new Student { Id = 3, Name = "铁蛋" }
            };
            List<Student> students2 = new List<Student>
            {
                new Student { Id = 1, Name = "张三" },
                new Student { Id = 3, Name = "狗剩" },
                new Student { Id = 5, Name = "二狗" }
            };

            var joinedStudents = students1.Join(students2,
                                                s1 => s1.Id,
                                                s2 => s2.Id,
                                                (s1, s2) => new 
                                                { 
                                                    Name1 = s1.Name, 
                                                    Name2 = s2.Name 
                                                });

            foreach (var student in joinedStudents)
            {
                Console.WriteLine($"Name1: {student.Name1}, Name2: {student.Name2}");
            }

            Console.ReadKey();
        }
    }

    class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

run:

In the above Join code, first look at the following two lines of code, here is to find a common key in two Lists, for example, s1 and s2 have a common key Id, here it will judge the value of Id between the two Whether there are the same values ​​in two Lists, the query result is also a set. As you can see from the above code, Id has two common values, 1 and 3.

s1 => s1.Id,
s2 => s2.Id,

The following code is a Lambda expression, which passes s1 and s2 as parameters to a new object. Name1 and Name2 are field names defined by themselves, and you can choose the name at will here

(s1, s2) => new 
{ 
    Name1 = s1.Name, 
    Name2 = s2.Name 
});

For example, if the name is like this, it will not report an error

After finding the set of the same fields, you can re-filter the data in this Lambda expression. We put the mouse on joinedStudents, and you can see that it is a class called 'a, which is the class we customized above.

Seventeen, ToList 

Convert a sequence to a List

In many of the above cases, the result of the query can be converted into a List. Let's look at a case, which is very simple.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            List<int> numList = new List<int> { 1, 4, 5, 24, 43, 67, 12, 90, 15 };
            List<int> list = numList.Where(x => x > 40).ToList();
            foreach (int num in list)
            {
                Console.WriteLine(num);
            }
            Console.ReadKey();
        }
    }
}

run:

Eighteen, ToArray

Convert sequence to Array

The usage of ToArray and ToList is similar, but the conversion result is different

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            List<int> numList = new List<int> { 1, 4, 5, 24, 43, 67, 12, 90, 15 };
            int[] ints = numList.Where(x => x > 40).ToArray();
            foreach (int num in ints)
            {
                Console.WriteLine(num);
            }
            Console.ReadKey();
        }
    }
}

run:

Nineteen, ToDictionary

Converts a sequence to a dictionary based on the specified key selector.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            List<People> peopleList = new List<People>()
            {
                new People(){Name="张三", Age=12, Career="学生" },
                new People(){Name="柱子", Age=25, Career="农民" },
                new People(){Name="铁蛋", Age=23, Career="农民" },
                new People(){Name="狗剩", Age=34, Career="职员" },
                new People(){Name="二狗", Age=28, Career="职员" },
            };
            Dictionary<string, People> peopleDictionary = peopleList.ToDictionary(x => x.Name);
            foreach (var kvp in peopleDictionary)
            {
                Console.WriteLine($"Key: {kvp.Key}, Value.Age: {kvp.Value.Age}");
            }

            Console.ReadKey();
        }
    }

    class People
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Career { get; set; }
    }
}

run:

end

Guess you like

Origin blog.csdn.net/qq_38693757/article/details/131707764