
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
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
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
- Related Articles
- Const cast in C++
- What is Cast Operator () in C#?
- What is a type cast in C/C++?
- Regular cast vs. static_cast vs. dynamic_cast in C++
- Regular cast vs. static_cast vs. dynamic_cast in C++ program
- C# Program to cast a type to its IEnumerable equivalent
- MySQL CAST as DATE?
- CAST function in Cassandra
- Why does C++ require a cast for malloc() but C doesn't?
- MySQL - CAST DECIMAL to INT?
- Difference between Cast and Splint
- How Can MySQL CAST handle overflow?
- How to use cast() in Android sqlite?
- Can we cast reference variables in Java?
- PHP How to cast variable to array?

Advertisements