Query a non-generic set by using Linq

Source: Internet
Author: User
In Linq to object, we can often easily query a variety of sets, such as List <T> generics, mainly because they all implement System. collections. generic. the IEnumerable <T> interface can complete related query operations, but not all classes have implemented the above interfaces, such as System. collections. arrayList, you can solve it in the following three ways.

I. OfType Operator
First, let's look at its signature public static IEnumerable <TResult> OfType <TResult> (this IEnumerable source) to filter IEnumerable elements based on the specified type. If source is null, ArgumentNullException is returned.

Var q = cars. OfType <Car> (). Where (c => c. Doors = 2 );

Ii. Cast forced conversion
From the signature of Cast, we can know that it can return IEnumerable <T>,
Public static IEnumerable <T> Cast <T> (this IEnumerable source)
However, if the type to be converted cannot be converted to T, Invalid-
CastException exception. If it is null, It is NullReferenceException. The code above is rewritten:

Var q = from c in cars. Cast <Car>
Where c. Doors = 2
Select new {c. Name}

Iii. Clear Type Definitions
Define the query type in from, as shown in figure


Var q = from Car c in cars
Where c. Doors = 2
Select new {c. Name}

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.