LINQ Common Query Operators

Source: Internet
Author: User

LINQ contains a total of more than 50 query operators, commonly used according to the type to distinguish between 5 categories, some of these five kinds of things in the project query often used. However, the naming of LINQ operators is very normative, basically from the literal meaning can guess what is the use of, below we choose some common to introduce. According to the classification we can be divided into the following 4 types:

1. Returns the ienumerable<t> type of

1.1 Where: used primarily for filtering of sequences, as in SQL for data filtering usage

1 int 1 3 5 7 2  }; 2 var 2 // Output 3,5,7,2

1.2 OfType: This is also used to filter the data, where the difference is in the filtering of a type of data, based on the specified type of IEnumerable element

1list<Object> list =Newlist<Object>();2List. ADD ("Power");3List. ADD (1);4 list.  ADD (DateTime.Now); 5 varquery = 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 that throws an exception when the conversion is unsuccessful

1 New  2 al. ADD (3 al. ADD (+); 4 al. ADD ("df"// throw System.InvalidCastException exception

1.4 Orderby,thenby,orderbydescending,thenbydescending: These are sort, sort, sort. The only thing to be aware of is that ThenBy is an extension method defined above iorderedenumerable<t>, because it cannot be called directly on ienumerable<t>, and ThenBy calls can only be queued

1 New List<product>(); 2 List2. ADD (new12}); 3 List2. ADD (new  ); 4 List2. (p = p.index). ThenBy (p = p.value);

1.5 Select: A projection operation is implemented, in which the object type can be converted. For example, in a Select object, convert it to the type we want

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


1.6 Take,skip:skip is to skip a few elements, take is a few elements, these two things for pagination, for example, we want to skip the previous 10 rows of data, take the next 10 rows of data

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


1.7 TakeWhile (), SkipWhile ():

TakeWhile returns the element that meets the criteria before encountering an element that does not meet the criteria

1 int [] arr = {14823,1}; 2 var 3 // Output 1  

SkipWhile will skip the qualifying element until it encounters the first element that does not meet the criteria, and then takes all the elements that follow the element

1 var 3); // Output  4  8 2 3 1


1.8 Reverse () to reverse the order of elements in a sequence

1.9 DefaultIfEmpty () when the sequence is empty, DefaultIfEmpty adds a default value or a specified value, which is useful in a LEFT join or right join, and when it is null, we can specify his value

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

1.10 Distinct () is mainly used to de-repeat sequences

1 int [] arr = {1233}; 2 var query2 = arr. Distinct (); 3 Query2. ToList (). ForEach (p=> Console.Write (p)); // Output 1  2  3  

The type of int can be de-duplicated because the int type inherits the IComparable, and if we want to repeat a field of a class, we can call an overloaded method of distinct, passing the inheritance to iequalitycomparer<t> The class

1  Public classProductcomparer:iequalitycomparer<product>2 {3      Public BOOLEquals (Product A, product B)4    {5        returnA.index = =B.index;6    }7 8     Public intGetHashCode (Product obj)9    {Ten        returnobj. Index; One    } A } -  - Public classProduct the{ - Public intIndex {Get;Set; } -} -  +   -  +product[] Array =New[]{ at                 NewProduct () {Index =1}, -                 NewProduct () {Index =2}, -                 NewProduct () {Index =2}, -                 NewProduct () {Index =3} -             }; -   in  -Productcomparer PC =Newproductcomparer (); to varQuery2 = array. Distinct (PC);//Output 1 2 3

1.11 GroupBy: In SQL, group by can only be used in conjunction with aggregate functions, but in LINQ, GroupBy comes out as a tree structure.

1list<product> list =NewList<product>()2 {3     NewProduct () {Index =1, Value =1},4     NewProduct () {Index =2, Value =2},5     NewProduct () {Index =2, Value =3},6     NewProduct () {Index =3, Value =3},7     NewProduct () {Index =4, Value =5},8 };9 Ten varQuery2 = list. GroupBy (p =p.index). ToList (); One  A foreach(varIteminchQuery2) - { -Console.Write (item. key+"-"); the     foreach(varProductinchItem) -     { - Console.Write (product. Value); - Console.WriteLine (); +     } -}//output 1-1 2-2 3 3-3 4-5

1.12 Intersect (), Except (): Intersect is a sequence that returns the same elements in two sequences, and Except the opposite

1 int [] arr1 = {123}; 2 int 2 5 6  }; 3 var // Output  2

1.13 Concat (), Union (): Concat for connecting two sequences, union is also connecting two sequences, but the same items are excluded

1.14 Zip (): The element with the same index in the two sequence, forming a new element, whichever is shorter

1 int[] arr = {1,2,3,4};2 string[] arr2 = {"a","two","three","Four","Five"};3 varquery = arr. Zip (ARR2, (x, y) = =string. Format ("{0},{1}", x, y));4 //Output 1, 12, 23, 34, four

2. Return other sequence types

Toarray,tolist,todictionary,tolookup these are converted ienumerable<t> to the corresponding type, as usual ToList, no delay loading, immediately return.

3. Returning elements in a sequence

3.1 ElementAt (), Elementatordefault (): ElementAt (index) returns the element with the subscript value index, throws an exception if it does not exist, Use Elementatordefault to return the default value of this type to resolve the exception condition

3.2 (), FirstOrDefault (): First returns a sequence element that satisfies the condition, throws an exception if it does not exist, and uses the FirstOrDefault to return the default value of that type to resolve the exception condition

3.3 Last (), LastOrDefault (): Finally returns the final sequence element that satisfies the condition, throws an exception if it does not exist, and uses the LastOrDefault to return the default value of that type to resolve the exception condition

3.4 single (), Singleordefault (): A is a bit different from the above, it requires that there is only one item in the sequence that satisfies the condition, and throws an exception when it is greater than one. Singleordefault is used to return a type default value when the query result is 0 items.

4. Return a scalar value

4.1 Count (), LongCount (), Max (), Min (), Average (), Sum (): These estimates are very familiar to us, and by literal means we can see the example:

1 int[] arr = {1,2,3,4};2 intQuery1 =arr. Count ();3Console.WriteLine (Query1);//Output 44 5 intQuery2 =arr. Max ();6Console.WriteLine (Query2);//Output 47 8 intQuery3 =arr. Min ();9Console.WriteLine (Query3);//Output 1Ten  One DoubleQuery4 =arr. Average (); AConsole.WriteLine (QUERY4);//Output 2.5 -  - intsum =arr. Sum (); theConsole.WriteLine (sum);//Output Ten

4.2 Aggregate (): Returns a custom aggregation, such as multiply by 2 for each element, and then add

1 int sum2 = arr. Aggregate (0, (total, x) = Total + (x*2)); 2 Console.WriteLine (  sum2);   Output

4.3 Contains (), any (), all (), sequenceequal ()

Contains: Determining whether an element exists in a sequence

Any: Determines whether there are elements in the sequence that satisfy an expression, and returns True if an element satisfies it. We often judge a list is not empty, use list.count! =0, this is a waste of performance because it will be to count the list of all the number, when we use any, as long as the first element can be judged

All: Determines whether all elements in the sequence satisfy the expression, and returns Fasle if one is not satisfied

SequenceEqual: Used to compare two sequences one by one, returns true if the number of elements in the two sequence is the same, and the element position is the same, otherwise false


Thank you for watching, I wish you a happy 2016!

LINQ common Query operators

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: 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.