C # basic operations for querying by using Linq

Source: Internet
Author: User

Abstract: This topic describes basic operations for querying a table by using a query keyword) -from clause-where clause-select clause-group clause-into clause-orderby clause-join clause-let clause-composite from clause-in some cases, each element in the source sequence may be a sequence (SET ), it may also contain sequence-term access to an internal set in a single database-use multiple from statements to execute connections-it can contain multiple from statements that can generate supplementary queries from an independent data source (as the name suggests, there are multiple from statements) instance: class Program {static void Main (string [] args) {List <Student> students = new List <Student> {new Student {LastName = "xiaogui ", scores = new List <int> {97,42, 9 }}, New Student {LastName = "xiaozhan", Scores = new List <int> {50, 92, }}, new Student {LastName = "xiaolan ", scores = new List <int >{32, 32, }}, new Student {LastName = "xiaowan", Scores = new List <int >{92,22 }},}; var query = from stuent in students from score in stuent. scores where score> 90 select new {Last = stuent. lastName, score}; foreach (var student in query) // displays {Console if the score is greater than 90. W RiteLine ("{0} Score: {1}", student. last, student. score);} Console. readLine () ;}} public class Student {public string LastName {get; set;} public List <int> Scores {get; set ;}} public class Employee {public string First {get; set;} public string Last {get; set;} public int ID {get; set ;}} execution result: xiaogui Score: 97 xiaogui Score: 91 xiaozhan Score: 92 xiaowan Score: 92 let keywords (extend range variables using let words)-create An enumerative type that can query itself-so that the query can only call ToLower once for the range variable word. If you do not use let, you must call the ToLower example in each predicate of the where clause to find out the using System; using System that contains a or e at the beginning of each word. linq; public class Test {static void Main (string [] args) {string [] strings = {"A penny saved is a penny earned. "," The aaxly sdj "," the pa is no "}; var query = from sentence in strings let words = sentence. split ('') // use spaces to Split the string into arrays from word in words let w = word. toLower () // lowercase where w [0] = 'A' | w [0] = 'E' sele Ct word; foreach (var s in query) {Console. writeLine (s);} Console. readLine () ;}} where keyword (filter)-a query expression can contain multiple where statements for example: (find out a) using System; using System. linq; public class Test {static void Main (string [] args) {string [] str = {"a", "B", "c "}; var query = from s in str where s = "a" select s; foreach (var s in query) {Console. writeLine (s);} Console. readLine () ;}} orderby keyword (SORT)-in the query In an expression, the orderby clause can sort the returned sequence (Group) in ascending or descending order. -You can specify multiple keys to execute one or more secondary sorting operations. The default sorting order is ascending. At the time of compilation, the orderby statement is converted to a call to the OrderBy method. Multiple keys in the orderby clause are converted to the ThenBy method. The descending order ascending is called. Example 1: ascending order using System; using System. linq; public class Test {static void Main (string [] args) {string [] str = {"a", "B", "c "}; var query = from s in str orderby s ascending select s;} result: a B c Example 2: using System in descending order; using System. linq; public class Test {static void Main (string [] args) {string [] str = {"a", "B", "c "}; var query = from s in str Orderby s descending select s;} returns an IGrouping (TKey, Telement) object sequence, the group clause is converted to a call to the GroupBy method (the LINQ query expression can end with select or Group) (if you want to perform additional query operations on each group, you can use the into context keyword to specify a temporary identifier. When using into, you must continue to write the query and end the query with a select statement or another group clause.) Example: using System; using System. linq; public class Test {static void Main (string [] args) {string [] str = {"aa", "bb", "cc", "dd "}; var query = From s in str group s by s [0] into p where p. key = 'A' | p. key = 'B' | p. key = 'C' orderby p. key descending select p. key; foreach (var s in query) {Console. writeLine (s);} Console. readLine () ;}}result: c B a description: group s by s [0] into p indicates that the range variable s is grouped by "s [0, in this example, join keywords are grouped by the first letter) -The join clause can be used to associate elements from different source sequences without any direct relationships in the object model. The only requirement is that the elements in each source need to be shared and can be compared to determine whether or not equal Value-join clause use special equals keyword to compare whether the specified key is equal Common connection types in section 3-Internal join-Group join-left Outer Join 1. internal join var query = from a in str join B in str2 on. id equals B. id select new {Aname =. name, Bname = B. name}; 2. group join: (into can store join temporarily) var query = from a in str join B in str2 on. id equals B. id into c select new {Aname =. name, Cs = c} 3. left Outer Join-in the left Outer Join, all elements in the left source sequence are returned, even if they are not matched in the right sequence. -To execute a left external join in LINQ, combine the DefaultifEmpty method with the Group join method, to specify the default right-side element generated when a left-side element does not have a matching element. You can use null as the default value of any reference type or specify the default type defined by the user. Var query = from category in categories join prod in products on category. id equals prod. categoryID into prodGroup from item prodGroup. defaultifEmpty (new Product {Name = string. empty, CategoryID = 0}) select new {CatName = category. name, ProdName = item. name} else se operator-join clause executes equal join. In other words, matching can only be performed based on the equality relationship between two keys-to indicate that all joins are equal joins, the join clause uses the equals keyword instead of the = Operator

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.