LINQ standard Query Operator (iv)-asenumerable,cast,oftype,toarray,todictionary,tolist,tolookup,first,last,elementat

Source: Internet
Author: User

This article from: http://blog.csdn.net/xuejianwu/article/details/6931926

X. Conversion operators

Conversion operators are used to implement the ability to convert the type of an input object into a sequence. The conversion method whose name starts with "as" changes the static type of the source collection but does not enumerate (lazy-load) this source collection. The method that begins with the name "to" enumerates the source collection and puts the items into the appropriate collection type.

1. AsEnumerable

All types that implement the Ienumerable<t> interface can call this method to get a ienumerable<t> collection. This method is typically used only when the method in the implementation class has the same name as the Ienumerable<t> interface method. For example, there is a where method in the implementation class test that executes the Where method procedure of the test itself when the where is invoked using the test object. If you want to execute the where method of the ienumerable<t>, you can use AsEnumerable to do the conversion, and then call the Where method. Of course, the implementation class test is implicitly converted to the Ienumerable<t> interface, and the where method of invoking the interface can achieve the same effect. The following code demonstrates this process:

[CSharp]View Plaincopy
  1. Class Asenumerabletest<t>: list<t>
  2. {
  3. public void Where (func<t, bool> Func)
  4. {
  5. Console.WriteLine ("where method of Asenumerabletest");
  6. }
  7. }
  8. Public static void AsEnumerable ()
  9. {
  10. asenumerabletest<int> q = new asenumerabletest<int> () {1,2,3,4};
  11. Q.where (r = r < 3);
  12. //q.asenumerable ().  Where (r = r < 3);
  13. //ienumerable<int> i = q;
  14. //i.where (r = r < 3);
  15. }

2. Cast

The Cast<t> method calls the Cast<t> method on a IEnumerable (non-generic) derived object to obtain a Ienumerable<t> object by providing the necessary type information. For example, ArrayList does not implement IENUMERABLE<T>, but by invoking Cast<t> () on the ArrayList object, you can query the sequence using standard query operators.

If an element in the collection cannot be cast to type T, this method throws an exception. The following code demonstrates this process:

[CSharp]View Plaincopy
    1. ArrayList array = new ArrayList ();
    2. Array.  ADD ("Bob");
    3. Array.  ADD ("Jack");
    4. Array. ADD (1);
    5. foreach (var item in Array. cast<string> ())
    6. {
    7. Console.WriteLine (item);
    8. }

Running this code, you can output "Bob", "Jack", and then report an exception "cannot cast int to string", which means that the cast method is also deferred for implementation, and the object is cast to the T type individually only during the enumeration process.

3. OfType

OfType <T> method by providing the necessary type information, the OfType <T> method can be called on a IEnumerable (non-generic) derived object to obtain a Ienumerable<t> object. The Execute Oftype<t> method returns all elements of the collection that have succeeded in casting the type. That is, the difference between the,oftype<t> method and the Cast<t> method is that if the elements in the collection are skipped when the cast fails, instead of throwing an exception.

4. ToArray

The ToArray operator can be called on any derived object of the ienumerable<t> type, and the return value is an array of type T.

5. ToDictionary

The todictionary operator creates a dictionary<tkey, tvalue> from Ienumerable<t>, based on the specified key selector function. In the following example, the query to a collection of product categories is converted to the dictionary< category ID, the category name > key-Value collection:

[CSharp]View Plaincopy
  1. using (NorthwindDataContext db = new NorthwindDataContext ())
  2. {
  3. Db. Log = Console.Out; //Outputs the generated T-SQL statements to the console
  4. //Method Syntax
  5. var q =
  6. Db. Categories
  7. . ToDictionary
  8. (
  9. c = C.categoryid,
  10. c = C.categoryname
  11. );
  12. foreach (var item in q)
  13. {
  14. Console.WriteLine ("{0}-{1}", item. Key,item.  Value);
  15. }
  16. }

Note that if you omit the second argument (value selection function) of the ToDictionary method, value will save a Category object. Also, if key is null, or if a duplicate key appears, it will cause an exception to be thrown.

6. ToList

The tolist operator can be called on any derived object of the ienumerable<t> type, returning an object with a value of list<t> type.

7. ToLookup

The tolookup operator creates a lookup<tkey, Telement> object, which is a One-to-many collection, and a key can correspond to more than one value. The following example takes all the data from the product table as a data source, invokes the ToLookup method with the category ID as key, and then iterates through the returned Lookup<tkey, Telement> object, outputting the category ID and all the product names under this category:

[CSharp]View Plaincopy
  1. using (NorthwindDataContext db = new NorthwindDataContext ())
  2. {
  3. Db. Log = Console.Out; //Outputs the generated T-SQL statements to the console
  4. //Method Syntax
  5. var q =
  6. Db. Products
  7. . ToLookup
  8. (
  9. p = P.categoryid,
  10. p = P.productname
  11. );
  12. foreach (var item in q)
  13. {
  14. Console.WriteLine (item. Key);
  15. foreach (var p in item)
  16. {
  17. Console.WriteLine (P);
  18. }
  19. }
  20. }

As you can see, the tolookup operation is very similar to the groupby operation, except that the groupby is delayed loading, and tolookup is even loaded.

Xi. element operator

The element operator returns a single specified element from a sequence.

1. First

The first operation returns one element in the sequence. If the sequence does not contain any elements, the First<t> method throws an exception. To return a default value when the source sequence is empty, you need to use the FirstOrDefault method. The following code demonstrates how the First<t> method is used:

[CSharp]View Plaincopy
  1. using (NorthwindDataContext db = new NorthwindDataContext ())
  2. {
  3. Db. Log = Console.Out; //Outputs the generated T-SQL statements to the console
  4. //No reference
  5. var query =
  6. Db. Employees
  7. . First ();
  8. //With reference
  9. var q =
  10. Db. Employees
  11. .  First (E = E.firstname.startswith ("S"));
  12. Console.WriteLine (Q.firstname);
  13. }

The above code uses the First<t> method and the argument mode. The first<t> can specify a condition in which the action returns the first element in the sequence that satisfies this condition. From the query results, source. First<t> (conditional) method with source. Where (condition). First<t> () is the same, but it is important to note that the "first<t> (conditional) operation returns the first element in the sequence that satisfies this condition", which ignores subsequent traversal operations and is more efficient.

2. FirstOrDefault

The FirstOrDefault method returns the first element in the sequence, or a default value if the sequence contains no elements. It can also pass a condition just like the first method. It is necessary to note that if the sequence does not contain any elements, the default value returned is what kind of an element. Before that, let's take a look at how the FirstOrDefault method is implemented:

[CSharp]View Plaincopy
  1. Public static TSource firstordefault<tsource> (thisienumerable<tsource> source)
  2. {
  3. if (Source = = null)
  4. {
  5. throw Error.argumentnull ("source");
  6. }
  7. ilist<tsource> list = source as ilist<tsource>;
  8. if (list! = null)
  9. {
  10. if (list. Count > 0)
  11. {
  12. return list[0];
  13. }
  14. }
  15. Else
  16. {
  17. using (ienumerator<tsource> enumerator = source. GetEnumerator ())
  18. {
  19. if (enumerator. MoveNext ())
  20. {
  21. return Enumerator.  Current;
  22. }
  23. }
  24. }
  25. return default (TSource);
  26. }

1. Throws an exception if the sequence that calls the FirstOrDefault method is empty

2. If the sequence is successfully converted to LIST<T>, and the number of elements is greater than 0, return to the element

3. If the sequence is not successfully converted to LIST<T>, then an attempt is made to get the sequence's walker, and then the MoveNext method of the Walker is called, and if the return value is true, the current element is returned.

4. If none of the above actions have been performed, return the default value of type T using the default (t) keyword

The following is a description of the default (T) keyword in MSDN:

One problem that arises in generic classes and generic methods is how to assign a default value to a parameterized type T when the following conditions are not known in advance:

    • T is a reference type or a value type.
    • If T is a value type, then it is numeric or structure.

Given a variable t of the parameterized type T, the statement t = NULL is valid only if T is a reference type, and the statement t = 0 is used only when T is a numeric type and not a struct. The solution is to use the default keyword, which returns null for reference types and zero for numeric types. For structs, this keyword returns each struct member initialized to zero or null, depending on whether the structure is a value type or a reference type.

3. Last

The last method returns the final element in the sequence. Use the method to refer to first.

4. LastOrDefault

The LastOrDefault method returns the last element in the sequence, or a default value if the sequence contains no elements. Use the method to refer to FirstOrDefault.

5. ElementAt

The ElementAt method returns the element at the specified index in the sequence. Use the method to refer to first. It is important to note that if an index goes out of scope, it causes an exception.

6. Elementatordefault

The Elementatordefault method returns the element at the specified index in the sequence, or a default value if the index is out of range. Use the method to refer to FirstOrDefault.

7. Single

The non-parametric form of the single method returns an individual element from a sequence that throws an exception if the sequence contains more than one element, or if no number of elements is 0. That is, when the sequence executes the parameterless form of a single method, it must be guaranteed that the sequence has only one element.

The argument form of the single method returns the unique element that conforms to the specified condition from a sequence, and throws an exception if there are multiple elements, or if no element meets this condition. The following code demonstrates how a single is used:

[CSharp]View Plaincopy
  1. using (NorthwindDataContext db = new NorthwindDataContext ())
  2. {
  3. Db. Log = Console.Out; //Outputs the generated T-SQL statements to the console
  4. //Method Syntax
  5. var q =
  6. Db. Employees
  7. . Single ();
  8. var query =
  9. Db. Employees
  10. .  Single (E = E.firstname.startswith ("S"));
  11. Console.WriteLine (query. FirstName);
  12. }

8. Singleordefault

The non-parametric form of the Singleordefault method returns a single element from a sequence. If the number of elements is 0, the default value is returned. If the sequence contains more than one element, an exception is thrown.

The argument form of the Singleordefault method returns a unique element that conforms to the specified condition from a sequence, and returns a default value if the number of elements is 0, or an exception if the sequence contains more than one element. The Singleordefault is used in the same way as single.

It should be noted that both the single method and the Singleordefault method are loaded immediately, and if an exception is thrown when the code is in the location of the method, it is thrown at once.

LINQ standard Query Operator (iv)-asenumerable,cast,oftype,toarray,todictionary,tolist,tolookup,first,last,elementat

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.