Converting Data Types (C#)

Conversion methods change the type of input objects.

Conversion operations in LINQ queries are useful in a variety of applications. Following are some examples:

Methods

The following table lists the standard query operator methods that perform data-type conversions.

The conversion methods in this table whose names start with "As" change the static type of the source collection but do not enumerate it. The methods whose names start with "To" enumerate the source collection and put the items into the corresponding collection type.

Method Name Description C# Query Expression Syntax More Information
AsEnumerable Returns the input typed as IEnumerable<T>. Not applicable. Enumerable.AsEnumerable
AsQueryable Converts a (generic) IEnumerable to a (generic) IQueryable. Not applicable. Queryable.AsQueryable
Cast Casts the elements of a collection to a specified type. Use an explicitly typed range variable. For example:

from string str in words
Enumerable.Cast

Queryable.Cast
OfType Filters values, depending on their ability to be cast to a specified type. Not applicable. Enumerable.OfType

Queryable.OfType
ToArray Converts a collection to an array. This method forces query execution. Not applicable. Enumerable.ToArray
ToDictionary Puts elements into a Dictionary<TKey,TValue> based on a key selector function. This method forces query execution. Not applicable. Enumerable.ToDictionary
ToList Converts a collection to a List<T>. This method forces query execution. Not applicable. Enumerable.ToList
ToLookup Puts elements into a Lookup<TKey,TElement> (a one-to-many dictionary) based on a key selector function. This method forces query execution. Not applicable. Enumerable.ToLookup

Query Expression Syntax Example

The following code example uses an explicitly typed range variable to cast a type to a subtype before accessing a member that is available only on the subtype.

class Plant
{
    public string Name { get; set; }
}

class CarnivorousPlant : Plant
{
    public string TrapType { get; set; }
}

static void Cast()
{
    Plant[] plants = new Plant[] {
        new CarnivorousPlant { Name = "Venus Fly Trap", TrapType = "Snap Trap" },
        new CarnivorousPlant { Name = "Pitcher Plant", TrapType = "Pitfall Trap" },
        new CarnivorousPlant { Name = "Sundew", TrapType = "Flypaper Trap" },
        new CarnivorousPlant { Name = "Waterwheel Plant", TrapType = "Snap Trap" }
    };

    var query = from CarnivorousPlant cPlant in plants
                where cPlant.TrapType == "Snap Trap"
                select cPlant;

    foreach (Plant plant in query)
        Console.WriteLine(plant.Name);

    /* This code produces the following output:

        Venus Fly Trap
        Waterwheel Plant
    */
}

See also