Table of contents
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 III - 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.
Twenty, SelectMany
SelectMany is used to expand nested collections into a flat sequence
This explanation is a bit difficult to understand, it is best to explain it with a case
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqTest
{
internal class Program
{
static void Main(string[] args)
{
List<Student> students = new List<Student>
{
new Student { Id = 1, Name = "John", Courses = new List<string> { "Math", "English" } },
new Student { Id = 2, Name = "Jane", Courses = new List<string> { "Science", "History" } },
new Student { Id = 3, Name = "Mike", Courses = new List<string> { "Art", "Music" } }
};
var allCourses = students.SelectMany(s => s.Courses);
foreach (var course in allCourses)
{
Console.WriteLine(course);
}
Console.ReadKey();
}
}
class Student
{
public int Id { get; set; }
public string Name { get; set; }
public List<string> Courses { get; set; }
}
}
run:
21. Aggregate
Accumulates the elements of a sequence using the specified accumulator function.
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqTest
{
internal class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5 };
int sum = numbers.Aggregate((acc, num) => acc + num);
Console.WriteLine("结果:{0}", sum);
Console.ReadKey();
}
}
}
run:
In the sentence of Aggregate((acc, num) => acc + num), we can see that there are two parameters, so it takes two parameters first, 1 + 2 = 3, and then takes 3 + 3 = 6, and so on, the final result is equal to 15
Twenty-two, DistinctBy
DistinctBy is a custom extension method, which is used to deduplicate the elements in the sequence according to the specified attribute or condition.
The de-duplication operation looks a bit confusing, but it actually removes duplicate elements. There are many ways to use this method, and you can find many ways to play, but I basically don’t use it, haha.
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqTest
{
internal class Program
{
static void Main(string[] args)
{
List<Person> people = new List<Person>
{
new Person { Id = 1, Name = "John" },
new Person { Id = 2, Name = "Jane" },
new Person { Id = 3, Name = "John" }
};
var distinctPeople = people.DistinctBy(p => p.Name);
foreach (var person in distinctPeople)
{
Console.WriteLine(person.Name);
}
Console.ReadKey();
}
}
class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public static class EnumerableExtensions
{
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
}
}
run:
23. Reverse
Returns the elements of the sequence in reverse order.
This is very simple, go directly to the case
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqTest
{
internal class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5 };
var reversedNumbers = numbers.Reverse();
foreach (var number in reversedNumbers)
{
Console.WriteLine(number);
}
Console.ReadKey();
}
}
}
run:
24. SequenceEqual
SequenceEqual is used to compare two sequences for equality.
In this method, the two arrays must be exactly the same to return true, and the types must also be the same
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqTest
{
internal class Program
{
static void Main(string[] args)
{
int[] numbers1 = { 1, 2, 3, 4, 5 };
int[] numbers2 = { 1, 2, 3, 4, 5 };
bool areEqual = numbers1.SequenceEqual(numbers2);
Console.WriteLine(areEqual);
Console.ReadKey();
}
}
}
run:
25. Zip
zip is used to pair two sequences by index position.
In the following case, two arrays are added one by one, and a new array is regenerated according to the original subscript
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 = { 10, 20, 30 };
var zippedNumbers = numbers1.Zip(numbers2, (n1, n2) => n1 + n2);
foreach (var number in zippedNumbers)
{
Console.WriteLine(number);
}
Console.ReadKey();
}
}
}
run:
Twenty-six, SkipWhile
SkipWhile is used to skip elements in the sequence that satisfy the specified condition until the first element that does not meet the condition is encountered.
Note that the condition is not satisfied here. In the following cases, n refers to each element in the array. When n is traversed and does not meet the condition of n < 3, the set will be returned.
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqTest
{
internal class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5 };
var skippedNumbers = numbers.SkipWhile(n => n < 3);
foreach (var number in skippedNumbers)
{
Console.WriteLine(number);
}
Console.ReadKey();
}
}
}
run:
Twenty-seven, TakeWhile
TakeWhile is used to get consecutive elements in the sequence that satisfy the specified condition until the first element that does not meet the condition is encountered.
TakeWhile is just the opposite of SkipWhile, and it is relatively simple to use.
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqTest
{
internal class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5 };
var takenNumbers = numbers.TakeWhile(n => n < 4);
foreach (var number in takenNumbers)
{
Console.WriteLine(number);
}
Console.ReadKey();
}
}
}
run:
end