LINQ learning notes (1 ).

Source: Internet
Author: User
Tags tojson

LINQ learning notes (1 ).

Learning Resources reference: http://www.cnblogs.com/lifepoem/archive/2011/12/16/2288017.html

 

The common methods are Where, OrderBy, and Select.

The advanced point is GroupBy, Join

 

LINQ is mainly used to solve the interaction between various data types in the early stage, as well as the forloop scenario. For example, we always thought that List <Class> is not a table, but why should we perform classification conversion, can't you learn about js. After that, we used generic classes, reflection, and delegation to implement some convenient processing of different data formats (basically a bit like js ). Later, Microsoft unified everyone's approach and wrote the complete LINQ. Later, the development of LINQ was very good. It was also used TO perform CRUD operations without the need TO write SQL statements, it is now under entity framework.

 

Although it is so powerful, I will only enter some introductory articles here. This article is only for personal review. If you have any mistakes, please correct them. Please stay away from new users to avoid mistakes, haha.

Idea: I think the implementation principle is still using reflection, delegation, generic classes, and the calling logic is basically the same as that of js, which encapsulates forloop, then let you upload a function to operate on each row for modification and filtering. It's just that the syntax is adjusted with a parser, making it easy to read and write.

 

The following are some basic usage and explanations, which are presented in code.

The focus of where is an internal expression. If the result is true | false, true is retained, and false is filtered out (it will be applied to each row during parsing)
The purpose of select is to modify the result and return a new object (the resolution is applied to each row)
N in where and select () is a parameter, and m can be written. This parameter represents the value in List. If the value in List is an object, it is an object.

Code on

List <string> nameList = new List <string> {"keatkeat", "xinyao", "ahyou"}; // if I want to filter data and keep the letters with a length of 5, then I want to write the characters in uppercase // method syntax IEnumerable <string> result1 = nameList. where (n => n. length = 5 ). select (n => n. toUpper (); // query syntax var result = from name in nameList where name. length = 5 select name. toUpper (); string json = stoogesV3.toJson (result); // ["AHYOU"]

From the js perspective, we can understand it in this way.

Function List (array) {this. array = array; this. whereList = []; this. selectFn ;}; List. prototype. where = function (fn) {this. whereList. push (fn); // Add all where statements to return this;}; List. prototype. select = function (fn) {this. selectFn = fn; // only one select statement returns this;}; List. prototype. toList = function () {var result = []; // here, we are lazy and only return the Normal array var array = this. array; for (var I = array. length-1; I> = 0; I --) {var value = array [I]; var is_remove = this. whereList. some (function (fn) {return (fn (value) = false); // remove if one is false}); if (is_remove) {array. splice (I, 1);} else {var finalValue = (this. selectFn )? This. selectFn (value): value; // use selectFn to modify the final value result. unshift (finalValue) ;}} return result ;}; var nameList = new List (["keatkeat", "xinyao", "ahyou"]); var result = nameList. where (function (n) {return n. length = 5 ;}). select (function (n) {return n. toUpperCase ();}). toList (); alert (result );

 

OrderBy

// Use thenBy to connect to the List <Person> list = new List <Person> {new Person {name = "keatkeat", age = 18 }, new Person {name = "xinyao", age = 19}, new Person {name = "ahyou", age = 17}, new Person {name = "bhyou2 ", age = 17}, new Person {name = "chyou2", age = 17 }}; var result = list. orderBy (n => n. age ). thenByDescending (n => n. name); var result1 = from person in list orderby person. age, person. name descending select person; string json = stoogesV3.toJson (result1 );

 

Subquery

Note that the subquery of LINQ to Object is executed every time the result is called. Therefore, the optimization method is to install the dependent value in the variable in advance, instead of running the subquery all the time.

String [] names = {"Tom", "Dick", "Harry", "Mary", "Jay "}; // The best practice is to take out int shorter = names first. min (n => n. length); var result = names. where (n => n. length = shorter); // obtain the names with the shortest Length (Note: there may be multiple names) var result1 = names. where (n => n. length = (names. min (g => g. length); var result2 = from n in names where n. length = (from n2 in names orderby n2.Length select n2.Length ). first () select n;

 

In other words, when we write a statement and do not call the result (such as toJson | foreach), it will not be executed until we call it, of course there is always another thing!

The following are some situations where statements can be executed directly.

 

Int [] numbers = {10, 9, 8, 7, 6}; int firstNumber = numbers. first (); // 10 int lastNumber = numbers. last (); // 6 int secondNumber = numbers. elementAt (1); // 9 int count = numbers. count (); // 5 int min = numbers. min (); // 6 int max = numbers. max (); // 10 bool hasTheNumberNine = numbers. contains (9); // true bool hasElements = numbers. any (); // true bool hasAnOddElement = numbers. any (n => (n % 2) = 1); // true, as long as one of

 

Concat vs union

Concat is to combine two lists

Union is also combine. However, union will automatically distict and filter out duplicate data. It is all distict after combine.

 

            int[] num1 = { 1, 2, 2, 3 };            int[] num2 = { 3, 4, 5 };            IEnumerable<int> concat = num1.Concat(num2);//[1,2,2,3,3,4,5]            IEnumerable<int> union = num1.Union(num2);//[1,2,3,4,5]

 

ToList

I just mentioned that LINQ is executed later. In order to optimize it, I can use ToList () to pack the result, but remember that it is still referenced instead of clone.

List <user> user_list = new List <user> {new user {name = "xinyao", age = 5}, new user {name = "keatkeat ", age = 10 }}; List <user> result = user_list.Where (n => n. name = "xinyao "). toList <user> (); // here the reference is saved

 

Common filter

// Skip and take can be used on the spot mysql limit 5 or 50, just like skip 5 take 50 string [] names = {"Tom", "Dick", "Harry", "Mary ", "Jay"}; var result = names. take (3); // The first three var result1 = names. skip (3); // The first three var result2 = names. takeWhile (n => n. length> 2); // obtain var result3 = names only after the condition. skipWhile (n => n. length> 2); // start skip with the header until var reuslt4 = names is obtained after the condition. distinct (); // filter out redundant duplicates

 

Find the difference

Returns the set of values that enum1 has but enum2 does not. Here, the header comparison uses reference =. That is to say, if the pointer is different, the value is the same and the value is false.

List <string> a = new List <string> {"a", "B"}; List <string> B = new List <string> {""}; var result =. except (B); // here the reference = is used. That is to say, the pointer value is not the same, so we can find the value that a has but B does not.

 

The next step is GroupBy, Join

We often use multiple select statements to retrieve the table because the SQL index is difficult to optimize. Then we can use join or groupBy to replace the SQL statement.

 

GroupBy idea

After running the GroupBy query, a group set is returned. Think about it as a table. After you set up the row group, it becomes like multiple tables, each table is divided into partial rows.

Therefore, in foreach result, each entry is a table-like set that contains a row with a good group.

GroupBy has many changes and focuses on understanding ideas.

List <Product> products = new List <Product> {new Product {code = "mk100", color = "red", size = "m "}, new Product {code = "mk100", color = "red", size = "s"}, new Product {code = "mk100", color = "yellow ", size = "s"}, new Product {code = "mk100", color = "yellow", size = "m"}, new Product {code = "mk100 ", color = "yellow", size = "l"}, new Product {code = "mk200", color = "red", size = "s "}, new Product {code = "mk200", color = "red", size = "m" },}; var result = products. groupBy (n => new {n. code, n. color }). select (n => new {code = n. first (). code, color = n. first (). color, size = String. join (",", n. select (m => m. size ))});
// You can directly obtain the value of the first row without repeating columns in the select statement. string json = stoogesV3.toJson (result) is returned );

 

Join is a little more complex.

In fact, join is suitable for writing "statements" instead of general "methods"
The statement looks much better.

Join is an inner join.

There are only some clever methods to implement left join.

Let's just talk about join. In the case of one-to-many, the row with multiple rows will be produced, and the row with 1 will be copied more, a bit of feel of Cartesian product.

If it is inner join, the row that cannot be matched will be deleted, and left join is to completely retain table a, even if some of its rows do not match table B.

Check the code.

Var result = from a in enum1 join B in enum2 on. name equals B. name // equals is equal to = where a ["name"]. toString () = "xinyao" // here you can add condition orderby a ["name"]. toString () select new {name = a ["name"]. toString (), like = B ["name"]}; // to obj var result1 = enum1.Join (enum2, // join table B a =>. name, // on a B => B. name, // on B (a, B) => new {name = a ["name"], like = B ["name"]} // final result ). where (n => n. name = "xinyao "). orderBy (n => n. name); // added later

Is it a lot worse? Can you see the following...

Left join:

The into keyword can also be changed. Here is just one method to use it.

Var result1 = from a in enum1 join B in enum2 on a ["name"] equals B ["name"] into x // here x is like, a is the row in enum1, not the table. // select x; do not select x directly, because x has deleted the row that does not match because of innerjoin, select new {name = a ["name"], row = x}; // we create a new object to add each row to favorites. If x is deleted, it should be a null value foreach (var zz in result1) {foreach (var yy in zz. row) {// If the on condition is not matched, zz. row is empty, so it won't come in here }}

 

Okay, there are a lot more left for the next article.

 


Plsql Study Notes 1

There are many brands of laptops, but from the recent computer warranty and after-sales service, the most important thing is the cost effectiveness, I recommend two brands of computers "Lenovo and HP"
Below I will introduce several computers, the landlord can consider,

Lenovo

Its Y430 series are among the first in terms of sales volume of computers and attention to the Ultimate Edition.
I want to introduce three models.
Y430a-pse

The configuration is as follows:
Processor Model Intel Core 2 dual-core P7450
Nominal clock speed 2.13 GHz
Front-End bus 1066 MHz
Level 2 Cache 3 MB
Kernel architecture Penryn
Platform technology Intel Platform
Motherboard chipset Intel PM45
Standard memory capacity 2 GB
Memory type DDRIII
Supports up to 4 GB memory
Hard drive/Optical Drive
Hard disk capacity 250 GB
Hard Disk description SATA
Optical Drive Type DVD recorder
Built-in design type Optical Drive
Graphics/sound effects
Low-end independent video card
NVIDIA GeForce 9300 m gs graphics chip
Stream processor count 16
Memory/Bit Width 256 MB/64 bit
Video memory type DDRII
Audio System built-in sound chip
Speaker Dolby certified sound effects, 2.1 audios (stereo speaker + subwoofer)
Display
Screen Size: 14.1 inch
Screen Ratio
Screen Resolution: 1280x800
Screen description LED WXGA
Size/weight
2350 GB laptop weight
Shape: 334x241x26-38mm
Case Material Composite Material
Network Communication
Wireless Network Card Intel 5100AGN
Nic description Mbps Nic
Support for Bluetooth
Modem 56 K
Red outer line infrared interface
Mouse/keyboard
Device touchpad
Keyboard description Lenovo notebook keyboard with high touch
Interface
USB interface: three USB Interfaces
Extended Interface ExpressCard
Card Reader-in-One Card Reader (SD/MMC, xD, MS, MS pro, SD Pro)
Video output HDMI high-definition port and standard VGA Interface
Other interfaces, such as 1394, RJ45, and full-array noise-resistant microphones, support for stereo audio headphone jack/audio output, and
Power supply description
Battery Type 6-core lithium battery
Power adapter 90 W power adapter
Others
Windows Vista Home Basic
Warranty Period: 3 years
Associated Software Package
Random attachment mouse
Optional accessory and notebook Gift Packs (purchased separately)
Other features: 1.3 million pixels support secure and easy-to-use Face Recognition
Quiet Mode with one click
Dolby audio 2.1 audio system
Electrostatic induction multimedia touch operation
Entertainment shuttle Sound Field Control
Hdmi hd output port
Other features: Lenovo one-click rescue/Lenovo flash link Ren Yitong
Environment requirements
Operating temperature 0-35 ℃
Operation humidity parameter error 10%-90% (no condensation)

The price is around 6100, which is definitely worth the money... In particular, it has good heat dissipation performance!

The second is y430-tfi.

Configuration
Intel Core 2 dual core T5800
Nominal 2 GHz clock speed
Front-End bus 800 MHz
Level 2 Cache 2 MB
Kernel architecture Merom
Platform technology: Intel®
Motherboard chipset Intel PM45
Standard memory capacity 2 GB
Memory type DDRIII
Supports up to 4 GB memory
Hard drive/Optical Drive
Hard disk capacity 250 GB
Hard Disk description SATA
Optical Drive Type DVD recorder
Built-in design type Optical Drive
Graphics/sound effects
Low-end independent video card
NVIDIA GeForce 9300 m gs graphics chip
Stream processor count 16
Memory/Bit Width 256 MB & #47 ...... remaining full text>
 
A notebook software? It is mainly used to record learning notes

The outlook provided by windows provides the daily Notebook function, which is easy to use.
And
The fish and fish table show is the first free desktop Widget software developed by Chinese people. Xforwarshow has a luxurious and elegant interface and powerful script engine, but occupies a very small amount of system resources. It is currently the fastest and most lightweight desktop widget tool. It adopts the plug-in mechanism, you can download a large number of Widgets on your desktop to implement functions such as weather forecast, World Clock, beautiful big icons on the desktop, calendar memos, notes, RSS news reading, cdcover player, and artistic the motto of desktop calligraphy and the goldfish used for traveling, make your Windows desktop more practical and colorful. The latest control-style Script Engine allows you to create diy widgets with unique personality!

[Features]
Supports weather forecast, daily (monthly) calendar, clock, RSS, notes, player control, Desktop shortcuts, and other functions. It also supports any combination of themes and unlimited extension of the plug-in mechanism.
Fast startup, low resource occupation, light and fast.
The original control-style Script Engine is simple and easy to use. It is the most DIY widget software.
Small, exquisite, and translucent embedded in the desktop background.
Many plug-ins are available on the home page. Double-click to automatically install the plug-in.
The built-in plug-in download browser automatically downloads and installs new plug-ins with one click.
Built-in real-time preview of the skin Editor, easy DIY personalized plug-ins, and support packaging and publishing plug-ins.
Beautiful and easy-to-use plug-in selection bar, plug-in startup animation expansion, supports fade in and fade out.
Huge user communities and Forum support.
More importantly, she is free!

: Cfishtest2.w29.1358.net/x?show_v=7.exe

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.