Commonly used query operators and commonly used Linq Operators

Source: Internet
Author: User

Commonly used query operators and commonly used Linq Operators

A total of more than 50 query operators are included in Linq, which are commonly used to differentiate between five types. Some of these five types are frequently used in project queries. However, the naming of the linq operator is very standard. It can be guessed from the literal meaning. Below we will introduce some common ones. Based on the classification, we can divide it into the following four types:

 

1. Return IEnumerable <T> type

1.1 Where: it is mainly used for filtering sequences. It is used in the same way as SQL for data filtering.

1 int [] array = {1, 3, 5, 7, 2}; 2 var query = array. where (p => p> = 2); // output 3, 5, 7, 2

 

1.2 OfType: This is also used to filter data. Different from where, it is used to filter a certain type of data and to filter IEnumerable elements based on the specified type.

1 List <object> list = new List <object> (); 2 list. add ("Power"); 3 list. add (1); 4 list. add (DateTime. now); 5 var query = list. ofType <string> (). where (p => p. startsWith ("P"); // output Power

 

1.3 Cast: defined on IEnumerable, used to convert a non-generic sequence into a generic sequence. If the conversion fails, an exception is thrown.

1 ArrayList al = new ArrayList (); 2 al. add (100); 3 al. add (1, 200); 4 al. add ("df"); // throw System. invalidCastException exception

 

1.4 OrderBy, ThenBy, OrderByDescending, and ThenByDescending: these are sorting, sorting, and sorting. The only thing to note is that ThenBy is an extended method defined in IOrderedEnumerable <T>, because it cannot be called directly on IEnumerable <T>. ThenBy can only be called after OrderBy.

1 List<Product> list2 = new List<Product>();2 list2.Add(new Product() {Index = 1,value = 2});3 list2.Add(new Product() { Index = 12 value = 22 });4 list2.OrderBy(p => p.Index).ThenBy(p => p.value);

 

1.5 Select: implements the projection operation, which can convert object types. For example, in the select object, convert it to the type we need

1 list2.Select (p => new Product {Index = p. Index}); // a new product object is created.

  

1.6 Take, Skip: skip skips several elements, and take takes several elements. These two elements are used for paging. For example, we want to Skip the data of the first 10 rows and retrieve the data of the last 10 rows.

1 var q = list.Skip(10).Take(10);

  

1.7 TakeWhile (), SkipWhile ():

When an element that does not meet the conditions is returned, TakeWhile returns the element that matches the conditions.

1 int [] arr = {1, 4, 8, 2, 3, 1}; 2 var query1 = arr. TakeWhile (x => x <= 3); // output 1

SkipWhile will skip the element that meets the condition until the first element that does not meet the condition is met, and then take all the elements after the element

1 var query2 = arr. SkipWhile (x => x <= 3); // output 4 8 2 3 1

  

1.8 Reverse () is used to sort the elements in the sequence in Reverse order.

 

1.9 DefaultIfEmpty () when the sequence is empty, DefaultIfEmpty adds a default value or a specified value, which is useful in left join or right join. When it is null, we can specify its value.

1 int [] arr ={}; 2 var query2 = arr. DefaultIfEmpty (); // output 0

 

1.10 Distinct () is mainly used for deduplication.

1 int [] arr = {1, 2, 3, 3}; 2 var query2 = arr. distinct (); 3 query2.ToList (). forEach (p => Console. write (p); // output 1 2 3

The reason that Int type can be de-duplicated is that Int type inherits IComparable. If we want to de-duplicate a field of a class, we can call an overload method of Distinct, passed the Class inherited from IEqualityComparer <T>

1 public class ProductComparer: IEqualityComparer <Product> 2 {3 public bool Equals (Product a, Product B) 4 {5 return. index = B. index; 6} 7 8 public int GetHashCode (Product obj) 9 {10 return obj. index; 11} 12} 13 14 public class Product15 {16 public int Index {get; set ;} 17} 18 19 20 21 Product [] array = new [] {23 new Product () {Index = 1}, 24 new Product () {Index = 2 }, 25 new Product () {Index = 2}, 26 new Product () {Index = 3} 27}; 28 29 30 ProductComparer pc = new ProductComparer (); 31 var query2 = array. distinct (pc); // output 1 2 3

 

1.11 GroupBy: in SQL, group by can only be used together with Aggregate functions, but in linq, what groupby comes out can be a tree structure.

1 List <Product> list = new List <Product> () 2 {3 new Product () {Index = 1, Value = 1}, 4 new Product () {Index = 2, Value = 2}, 5 new Product () {Index = 2, Value = 3}, 6 new Product () {Index = 3, Value = 3 }, 7 new Product () {Index = 4, Value = 5}, 8}; 9 10 var query2 = list. groupBy (p => p. index ). toList (); 11 12 foreach (var item in query2) 13 {14 Console. write (item. key + "-"); 15 foreach (var product in item) 16 {17 Console. write (product. value); 18 Console. writeLine (); 19} 20} // output 1-1 2-2 3 3-3 4-5

 

1.12 Intersect (), Except T (): Intersect returns a sequence consisting of the same elements in the two sequences, and limit t returns the opposite

1 int [] arr1 = {1, 2, 3}; 2 int [] arr2 = {2, 5, 6}; 3 var query2 = arr1.Intersect (arr2 ); // output 2

 

1.13 Concat (), Union (): concat is used to connect two sequences. union is also used to connect two sequences, but the same project is excluded.

 

1.14 Zip (): Create a new element with the same index in the two sequences. The length is subject to the shorter one.

1 int [] arr = {1, 2, 3, 4}; 2 string [] arr2 = {"1", "2", "3", "4 ", "5"}; 3 var query = arr. zip (arr2, (x, y) => string. format ("{0}, {1}", x, y); 4 // output 1, 1 2, 2 3, 3 4, 4

 

2. Return other Sequence Types

ToArray, ToList, ToDictionary, and ToLookUp all convert IEnumerable <T> to the corresponding type, just like the normal Tolist, without delay loading, and return immediately.

3. Return the elements in the sequence.

3.1 ElementAt (), ElementAtOrDefault (): ElementAt (index) returns the element with the index value. If it does not exist, an exception is thrown. ElementAtOrDefault is used to return the default value of this type to solve the exception.

3.2 First (), FirstOrDefault (): First returns the First sequence element meeting The condition. If it does not exist, an exception is thrown. Use FirstOrDefault to return the default value of this type to solve the exception.

3.3 Last (), LastOrDefault (): The Last sequence element that meets the condition is returned. If the element does not exist, an exception is thrown. Use LastOrDefault to return the default value of this type to solve the exception.

3.4 Single (), SingleOrDefault (): Single is a little different from the previous ones. It requires that there is only one item in the sequence that meets the conditions. If there is more than one item, an exception is thrown. SingleOrDefault is used to return the default type when the query result is 0.

4. Return Scalar Value

4.1 Count (), LongCount (), Max (), Min (), Average (), Sum (): We are very familiar with these estimates, let's take a look at the example:

1 int [] arr = {1, 2, 3, 4}; 2 int query1 = arr. count (); 3 Console. writeLine (query1); // output 4 4 5 int query2 = arr. max (); 6 Console. writeLine (query2); // output 4 7 8 int query3 = arr. min (); 9 Console. writeLine (query3); // output 110 11 double query4 = arr. average (); 12 Console. writeLine (query4); // The output is 2.513 14 int sum = arr. sum (); 15 Console. writeLine (sum); // output 10

 

4.2 Aggregate (): return a custom aggregation. For example, each element is multiplied by 2 and then added.

1 int sum2 = arr. Aggregate (0, (total, x) => total + (x * 2); 2 Console. WriteLine (sum2); // output 20

 

4.3 Contains (), Any (), All (), SequenceEqual ()

Contains: determines whether an element exists in a sequence.

Any: determines whether an element in the sequence meets the expression. If one element is satisfied, True is returned. We often use list. count if a list is not empty! = 0. This is a waste of performance because it will count the total number of the list. When we use any, we only need to judge the first element.

All: determines whether All elements in the sequence meet the expression. If one element is not satisfied, the return value is fasle.

SequenceEqual: used to compare two sequences one by one. If the number of elements in the two sequences is the same and the element position is the same, true is returned. Otherwise, false is returned.

 

End

Thank you for watching and wish you a Happy April 2016!

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.