preface

Remind: In order to be able to learn the knowledge more thoroughly, remember more firmly I will write down the knowledge by means of teaching on Because can let a person in the process from students to the teacher This process will be dug up new knowledge and ideas is a self thinking mining switch and a depth of knowledge and the process of ascension If you can help to everyone that is the best If there is something wrong, please give me more advice! I’m just a vegetable chicken thanks for understanding!


1. I first met LINQ

You’ve probably seen LINQ on the Internet or in a book, but what is it? Today, we will learn LINQ together

LINQ is a new feature integrated into languages such as C# and VB.net to provide the ability to query data

In a relational database, data is organized into the normative good table, and through the simple but powerful language SQL to access, process, however, in contrast to the database, stored in the data in a class object or structure difference is very big, so there is no general query to get the data from the data structure, the c # 3.0 after the introduction of LINQ, We now have the ability to query object data

LINQ is C# and gives us developers the ability to query data quickly

LINQ———– makes the language prettier, makes the queries easier, and makes the code better.


2. Simple LINQ case

Let’s start with an example to show you the beauty of LINQ

To use LINQ, refer to its namespace using system.linq;

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

namespace ConsoleApp1
{

    class GameText
    {
        public int gameID;                  / / game ID
        public string gameName;             // Game name
        public string gameIntduced;         // Game introduction
        public int gameSize;                // Game size
    }

    class Program
    {
        static List<GameText> game = new List<GameText>()
        {
            new GameText(){gameID = 1,gameName = "East and West",gameIntduced = "This is a 2D internship interview program.",gameSize = 1},
            new GameText(){gameID = 2,gameName = "You at my desk.",gameIntduced = "This is a youth school themed game.",gameSize = 5}};static void Main(string[] args)
        {

            var res = from m in game
                      where m.gameID > 1
                      select m.gameName;

            foreach (var item inres) { Console.WriteLine(item); }}}}Copy the code

Mainly look at this place

     var res = from m in game
          where m.gameID > 1
          select m.gameName;
Copy the code

From in are all keywords. Game is the object of the data that we’re looking for. M is the element in game

If the gameID is greater than 1, the gameID is greater than 1

Select m.gamename finds the game that meets the criteria and returns its game name

Let’s look at the output

The game ID is 1 and your ID is 2

where m.gameID > 1
Copy the code

Obviously, it’s you in the same seat and your game fits the bill so we end up with your game in the same seat

See is not very simple, oneself begin to knock can understand immediately!


3. Different syntax for LINQ

The previous example was about LINQ expressions, also called query syntax. Here we can also use method syntax to query data

Query syntax is declarative and looks similar to SQL statements. Query syntax is written in query expression form.

Method syntax is command form and uses standard method calls. Methods are a set of methods called standard query operators

As long as we refer to system.linq; We can call the Where method

There is an Enumerable class in the System.Linq namespace

The Enumerable class provides us developers with a plethora of methods to extend and share. It’s a bit too much to go into, but we’ll just go into the collection and then. Just call the where method inside

It requires us to pass in a Func delegate and there are two ways to write it

One way is to use Lambda expressions, the other way is to write a separate method, which is more cumbersome

So we’re going to write a method that takes GameText and returns a bool and we’re going to pass it to Where

//var res = from m in game
// where m.gameID > 1
// select m.gameName;

var res = game.Where(whereFunc);


foreach (var item in res)
{
    Console.WriteLine(item.gameName.ToString());
}


static bool whereFunc(GameText t)
{
    if (t.gameID > 1) return true;
    return false;
}

			
Copy the code

The output of the startup program is also the same as your old iron

Well, a few steps isn’t too much trouble, but Lambda expressions make it much simpler

//var res = from m in game
// where m.gameID > 1
// select m.gameName;

//var res = game.Where(whereFunc);

var res = game.Where(g => g.gameID > 1);

foreach (var item in res)
{
    Console.WriteLine(item.gameName.ToString());
}


//static bool whereFunc(GameText t)
/ / {
// if (t.gameID > 1) return true;
// return false;
/ /}

Copy the code

Or output the same seat you have no problem!

4. LINQ multi-table query operation

In order to do multiple table operations, we need to learn about join queries, and those of you who have studied SQL are probably familiar with joins, but I’m just dabbling in SQL, and I’m learning about joins for the first time, so what is it?

Join queries take two collections and create a temporary collection of objects. To join, each source object must share a value that can be compared to determine whether it is equal

Directly on the example a look at the example will understand

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

namespace ConsoleApp1
{

    class Gamer
    {
        public int id;
        public string playName;
    }

    class GameText
    {
        public string gameName;
        public int id;
    }

    class Program
    {
        static List<Gamer> game = new List<Gamer>()
        {
            new Gamer(){id = 0,playName = "Little red"},
            new Gamer(){id = 1,playName = "Black"},
            new Gamer(){id = 2,playName = "Little blue"},
            new Gamer(){id = 3,playName = "Yellow"},
            new Gamer(){id = 4,playName = "Small"}};static List<GameText> game2 = new List<GameText>()
        {
            new GameText(){gameName = "East and West",id = 1},
            new GameText(){gameName = "East and West",id = 4},
            new GameText(){gameName = "My seatmate.",id = 0},
            new GameText(){gameName = "My seatmate.",id = 2},
            new GameText(){gameName = "My seatmate.",id = 3}}; }}Copy the code

Now we have two classes

Gamer stores the player’s ID and name. GameText stores the name of the game and the ID of the player who played it

Now if we look at the game table, we can only get the name and ID of the player, but not the game that the player plays. In this case, we can use the join clause in LINQ.

static void Main(string[] args)
{

var res = from g in game
          join g2 in game2 on g.id equals g2.id
          where g2.gameName == "My seatmate."
          select new { playerName = g.playName, gameName = g2.gameName }; // Objects of anonymous type


    //var res = game.Where(g => g.gameID > 1);

    foreach (var item inres) { Console.WriteLine(item); }}Copy the code

In this section, we will discuss the operation of a JOIN

Join g2 in game2 exactly the same meaning as from G in game

From is followed by the object to be queried. Join is followed by the object to be joined. On is followed by the join condition

Select * from g2 where g2. GameName == g2.

Gamer stores the player’s ID and name. GameText stores the name of the game and the ID of the player who played it

They have the same ID and are playing your game with the same seat

Go back and see if our watch is red, blue and yellow. These three people are playing your game

Well, the output is fine

Here seems to have a called joint query, I did not understand the relationship between the two of them, the feeling is essentially the same is also can carry out multiple table query operation, wait for which elder brother teach brother!

I’m going to write out the union query here and nothing else is going to change

static void Main(string[] args)
{
    var res = from g in game
              from g2 in game2
              where g.id == g2.id && g2.gameName == "East and West"
              select new { playerName = g.playName, gameName = g2.gameName };

    foreach (var item inres) { Console.WriteLine(item); }}Copy the code

I don’t think it’s too hard to explain.


5. LINQ sorts the query results

The orderby clause is introduced here

The orderby clause takes an expression and returns the result item once based on the expression

The orderby clause defaults to ascending order, and we can also explicitly set the order of elements to ascending or descending using the ascending and descending keywords

Let’s take a look at an example

Order Derby G.i. D descending

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

namespace ConsoleApp1
{

    class Gamer
    {
        public int id;
        public string playName;
    }

    class GameText
    {
        public string gameName;
        public int id;
    }

    class Program
    {
        static List<Gamer> game = new List<Gamer>()
        {
            new Gamer(){id = 0,playName = "Little red"},
            new Gamer(){id = 1,playName = "Black"},
            new Gamer(){id = 2,playName = "Little blue"},
            new Gamer(){id = 3,playName = "Yellow"},
            new Gamer(){id = 4,playName = "Small"}};static List<GameText> game2 = new List<GameText>()
        {
            new GameText(){gameName = "East and West",id = 1},
            new GameText(){gameName = "East and West",id = 4},
            new GameText(){gameName = "My seatmate.",id = 0},
            new GameText(){gameName = "My seatmate.",id = 2},
            new GameText(){gameName = "My seatmate.",id = 3}};static void Main(string[] args)
        {
            var res = from g in game
                      join g2 in game2 on g.id equals g2.id
                      where g2.gameName == "My seatmate."
                      orderby g.id descending
                      select new { playerName = g.playName, gameName = g2.gameName };

            foreach (var item inres) { Console.WriteLine(item); }}}}Copy the code

Because by default our ID is 0, 1, 2, 3… So let’s reverse the data to see what happens

In ascending state, the output should be red, blue and yellow, and we use Order Derby G.I. D descending and press G.I. D to output the results in reverse order, so the output is yellow, blue and red