On the forum, people often ask ,linq How to implement recursion , How to find Cartesian product and so on .. Both can be used. linq Quick and convenient solution .. Now I'll make a general conclusion

1.） recursive

We often come across a situation , I want to get all the child nodes under the current node . For example, when we query , Guangdong is the best choice , So Guangzhou 、 Shenzhen 、 Dongguan is all in this range , Of course, it also includes the streets under Guangzhou . The first thing we think of is to come back and solve . But how to combine linq Well ？ Let's have a look

``` static List<City> list = new List<City>()
{
new City{id=1,name=" guangdong ",parentid=0},
new City{id=2,name=" Guangzhou ",parentid=1},
new City{id=3,name=" Shenzhen ",parentid=1},
new City{id=4,name=" dongguan ",parentid=1},
new City{id=5,name=" Yuexiu District ",parentid=2},
new City{id=6,name=" Baiyun District ",parentid=2},
};
static void Main(string[] args)
{
var result = GetChilds(list.First());
}
public static IEnumerable<City> GetChilds(City city)
{
var temp = list.Where(x => x.parentid == city.id);
return temp.Concat(temp.SelectMany(x => GetChilds(x)));
}```

Very simple. ？ Here we can just concat Front and back points 2 In part ,temp For the current city Child nodes of temp.selectmany There is to find the child node under the child node , So it's easy to understand

2.） The cartesian product

Think of Cartesian product , think first of selectmany To deal with it

``` static void Main(string[] args)
{
string[] s1 = { "A", "B", "C" };
string[] s2 = { "D", "E" };
var result = s1.SelectMany(x => s2.Select(y => x + y));
foreach (var item in result)
{
Console.WriteLine(item);
}
}```

The result is as we thought . But if it is 3 Or 4 Or more arrays ？ Maybe you think of circulation , Recursion, etc . But here I want to introduce you to one thing , It's called accumulator -Aggregate.

```static void Main(string[] args)
{
List<string[]> list = new List<string[]>();
string[] s1 = { "A", "B", "C" };
string[] s2 = { "D", "E" };
string[] s3 = { "F", "G" };
var result = list.Aggregate((thisCurrent, nextCurrent) => thisCurrent.SelectMany(x => nextCurrent.Select(y => x + y)).ToArray());
foreach (var item in result)
{
Console.WriteLine(item);
}
}```

Running results

It's tail recursion .

`(thisCurrent, nextCurrent) => thisCurrent.SelectMany(x => nextCurrent.Select(y => x + y)).ToArray()`
`thisCurrent.SelectMany(x => nextCurrent.Select(y => x + y)).ToArray() It will be passed to the next time as a parameter thisCurrent in `

3.） Group query Introduction

linq The grouping is very powerful , It's also great to use . For example, there's a group of people , We want to group them by their age , Every time 10 I'm divided into two groups , We will

``` static void Main(string[] args)
{
List<int> list = new List<int>()
{
6,7,8,9,12,15,18,23,25,33,31,39,40
};
var result = list.GroupBy(x => x / 10);
foreach (var item in result)
{
Console.WriteLine(string.Join(",", item));
}
}```

I won't take a screenshot here . It's very simple and rude .

But if we want to 1~18 Year olds are in the same group （ The children's group ）,18~28（ youth category ）,29~40 by （ Adult group ） So what should we do ？ Plus a gender , Divide into young women groups Young men's group, etc ,40 Men and women over the age of 18 , Unified homing elderly group . What should we do at this time ？LINQ It's still a simple and crude way to solve problems

``` public class Person
{
public string name { get; set; }
public int age { get; set; }
public string sex { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Person> list = new List<Person>()
{
new Person(){name=" Small A",age=5,sex=" male "},
new Person(){name=" Small B",age=5,sex=" Woman "},
new Person(){name=" Small C",age=7,sex=" male "},
new Person(){name=" Small D",age=12,sex=" male "},
new Person(){name=" Small E",age=20,sex=" Woman "},
new Person(){name=" Small F",age=21,sex=" male "},
new Person(){name=" Small G",age=25,sex=" male "},
new Person(){name=" Small H",age=39,sex=" male "},
new Person(){name=" Small I",age=55,sex=" male "},
new Person(){name=" Small J",age=54,sex=" Woman "},
};
var result = list.GroupBy(x =>
{
if (x.age <= 18)
return x.sex + " The children's group ";
if (x.age > 18 && x.age <= 28)
return x.sex + " youth category ";
if (x.age > 28 && x.age <= 40)
return x.sex + " Adult group ";
return " The elderly group ";
});
foreach (var item in result)
{
string name = string.Join(",", item.Select(x => x.name));
Console.WriteLine(string.Format("{0}:{1}", item.Key, name));
}
}```

Running results

I don't know if you have learned anything ..LINQ Very flexible , It depends on how you play .. Well used words can solve many complicated things in one sentence

## 2.Linq More articles on practical skills

1. FastReport Using skills

Using skills 1.FastReport If you access the objects in the report ?       have access to FindObject Method .      TfrxMemoView(frxReport1.FindObject('memo ...

2. 2 Heaven control DIV+CSS （ Tips ）（ turn ）

This is an article I saw last year , Feeling in my study , There's a lot of impact . So I want to share it with you soon css My brothers . This article is about skills . The basic chapter [ Knowledge one ] “DIV+CSS” It's not accurate [ Knowledge 2 ] “DIV+CSS” ...

3. LINQ to XML LINQ Learn the first

LINQ to XML LINQ Learn the first 1.LINQ to XML class The following code demonstrates how to use LINQ to XML To quickly create a xml: public static void CreateDoc ...

4. Visual Studio Debugging breakpoint skills section addendum

Original link address :http://blog.csdn.net/Donjuan/article/details/4649372 Finished Visual Studio After the breakpoint skills of debugging , I read some materials before and write them myself ...

5. Blend_ Tips _ Fade in and out

6. Blend_ Tips _ Import PSD Documentation ToggleButton （Z）

original text :Blend_ Tips _ Import PSD Documentation ToggleButton (Z) System : Win7sp1 32 position IDE: Microsoft VisualStudio 2013 Ultimate Ble ...

7. Gatling Scripting skills （ Two ）

Script example : import io.gatling.core.Predef._ import io.gatling.http.Predef._ import scala.concurrent.durati ...

8. 【Unity skill 】 Development skills （ Tips ）

Write it at the front Just like the memo , This article aims to summarize Unity Some design skills in development , Of course, this is just what I sum up from what I've seen and heard , If there is something wrong, please point out . skill 1: Put global constants in a separate script A lot of the time we need some constant ...

9. XSS Principle analysis and anatomy of : The third chapter （ Tips ）【 turn 】

0×01  Preface : About the first two sections url: Chapter one :http://www.freebuf.com/articles/web/40520.html Chapter two :http://www.freebuf.com/art ...

## Random recommendation

1. Swift - 2.3 Code to 3.0 The transformation of

Share some tips for learning new grammar : use Xcode8 Open your own Swift2.3 Project , choice Edit->Convert->To Current Swift Syntax- Give Way Xcode Help us to Swift ...

2. charles proxy

charles proxy   A good proxy tool , You can move data , as well as pc Data capture .

3. [Flex] ButtonBar series ——arrowKeysWrapFocus If the property is true, When using the arrow keys to navigate within the component , If it hits one end, it will turn back .

<?xml version="1.0" encoding="utf-8"?> <!--arrowKeysWrapFocus If true, ...

4. be based on visual Studio2013 solve C One of the questions in the language contest 0805 Achievement output

﻿﻿ subject

5. SIFT Gaussian blur in

Gauss fuzzy is one of many fuzzy algorithms , The so-called fuzziness , It's smoothing the image , Eliminate differences between pixels , The easiest way to think of it is mean smoothing . . The mean of fuzzy Mean blur is the average of the pixels around the target pixel . for example Pixel matrix . |1|1|1| |1 ...

6. Centos7 Start the specified docker The container reported an error

Do it today docker In the experiment , hold docker Mirror image pull Inferior posterior , The following error is reported during startup : error message :WARNING: IPv4 forwarding is disabled. Networking will not ...

7. ubuntu Installation on docker

author : headsen chen date : 2019-03-06  16:36:12 apt-get remove docker docker-engine docker-ce dock ...

8. python Requests Library network crawling IP Automatic search of address home

#IP Address query full code import requestsurl = "http://m.ip138.com/ip.asp?ip="try: r = requests.get(url + ...

9. tar Error in command compression tar: Removing leading `/&#39; from member names

In the use of tar When the command is compressed and packaged, we often encounter the following error . Although it won't affect our final compression package , But it indirectly shows that there is something wrong with our order . Now let's look at the solution . Wrong content : [root@haha ~]# ...

10. Memcahe Installation and configuration

1. Start... First Memcahe service (1) adopt Memcahe Under folder memcahe.exe Program started (2) take Memcahe Add to Windows In service For ease of use , Most of the time , It's the second way , To start up M ...