C# Cast method

CsharpProgrammingServer Side Programming

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
raja
Published on 14-Sep-2018 16:34:08
Advertisements