Cast

In this chapter you will learn:

  1. Use Linq Cast to convert array to IEnumerable
  2. Cast to int
  3. Cast and catch exception

Change data type with cast

using System;/*from  ja va 2s.  c  o m*/
using System.Linq;

public class MainClass{
   public static void Main(){
            object[] doubles = {1.0, 2.0, 3.0};
            IEnumerable<double> d = doubles.Cast<double>();
            Console.Write(d);
   }
}

Cast to int

using System;/*from j  a  v  a  2s .c  om*/
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        ArrayList classicList = new ArrayList();  // in System.Collections 
        classicList.AddRange(new int[] { 3, 4, 5 });
        IEnumerable<int> sequence1 = classicList.Cast<int>();
        foreach (int i in sequence1)
        {
            Console.WriteLine(i);
        }
    }
}

The output:

Cast and catch exception

When encountering an incompatible type Cast throws an exception;

using System;//  j  a  va2  s .  c  o m
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        ArrayList classicList = new ArrayList();  // in System.Collections 
        DateTime offender = DateTime.Now;
        classicList.Add(offender);
        IEnumerable<int> sequence1 = classicList.Cast<int>(); // Throws exception

        foreach (int i in sequence1)
        {
            Console.WriteLine(i);
        }
    }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How to use Concat operator
  2. Concatenate one array to another
  3. Concat vs Union
  4. Take then concatenate
Home » C# Tutorial » Linq Operators
Aggregate
Aggregate with seed
Aggregate string value
All
Any
Average
Cast
Concat
Contains
Count
DefaultIfEmpty
Distinct
ElementAt
ElementAtOrDefault
Empty
Except
FindAll
First
FirstOrDefault
GroupBy
Intersect
Last
LastOrDefault
LongCount
Max
Min
OfType
OrderBy
OrderByDescending
Range
Repeat
Reverse
SelectMany
SequenceEqual
Single
SingleOrDefault
Skip
SkipWhile
Sum
Take
TakeWhile
ThenBy
ThenByDescending
ToArray
ToList
Zip