| by Arround The Web | No comments

LINQ Cast() Method

Suppose in a Datasource there are elements with some data type and you want to convert them into types like string or double or integer, you can use the Cast() method.

Cast()

Cast() method in LINQ is used to cast/convert the data type in the existing data source to another data type. It will raise the exception if we convert them into different data types like string to integer etc.

Syntax:

input_source.Cast<datatype>()

Where:

  1. input_source can be any data source like ArrayList,List etc.
  2. data type is the type we will convert the type of the given data source.

Example 1:

Here, we will create a data source named Array List with Integer type and cast them into integer type.

So, the syntax should be:

input_source.Cast()
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;  

class Linuxhint {

  public static void Main()
    {
        //create an array list
        int[] my_arraylist={100,34,56,32,10,45};

        //display the ArrayList
        foreach (var result in my_arraylist){
Console.WriteLine(result);
        }
Console.WriteLine("------------------------");

//convert the array list collection to integer type
var final=my_arraylist.Cast();

//display
foreach (var result in final){
Console.WriteLine(result);
        }
    }
}

Output:

Explanation:

Create an array list named – my_arraylist.

Cast the my_arraylist to integer type.

Display the result using a foreach loop.

Example 2:

Here, we will create a data source named Array List with String type and cast them into string type.

So, the syntax should be:

input_source.Cast()
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;  

class Linuxhint {

  public static void Main()
    {
        //create an array list
        string[] my_arraylist={"Linuxhint","Java"};

        //display the ArrayList
        foreach (var result in my_arraylist){
Console.WriteLine(result);
        }
Console.WriteLine("------------------------");

//convert the array list collection to string type
var final=my_arraylist.Cast();

//display
foreach (var result in final){
Console.WriteLine(result);
        }
    }
}

Output:

Explanation:

Create an array list named – my_arraylist.

Cast the my_arraylist to string type.

Display the result using a foreach loop.

Conclusion

In this tutorial, we discussed the Cast() method. Cast() method in LINQ is used to cast/convert the data type in the existing data source to another data type. It will raise the exception if we convert them into different data types like string to integer etc. You have to specify the data types – int for integer, string for string and double for double type conversions.

Share Button

Source: linuxhint.com

Leave a Reply