C# Cast method


To cast elements, use the Cast() method.

The following is our list.

List<object> myList = new List<object> { "Mac", "Windows", "Linux", "Solaris" };

Now, cast and use the Cast() method with substring() method to display the first two letters of every string in the list.

IEnumerable<string> res = myList.AsQueryable().Cast<string>().Select(str => str.Substring(0, 2));

Let us see the complete example.

Example

 Live Demo

using System;
using System.Linq;
using System.Collections.Generic;
class Demo {
   static void Main() {
      List<object> list = new List<object> { "keyboard", "mouse", "joystick", "monitor" };
      // getting first 2 letters from every string
      IEnumerable<string> res = list.AsQueryable().Cast<string>().Select(str => str.Substring(0, 2));
      foreach (string str in res)
      Console.WriteLine(str);
   }
}

Output

ke
mo
jo
mo

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 23-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements