C# Tutorials

C# List Datatype to different Datatype

In this tutorial, we will discuss about how to change c# List data type to different data type. Normally, in other programming languages it is very easy to change List Data type. But in C# it is little tricky and slow as well.

Steps to change C# List Datatype


Here, I am taking a string C# list that we will convert into integer list.

Let’s suppose I have List variable with data type string. Now, add few string numbers in it as shown below

List<string> MyStringList = new List<string> {"1","2","3","4"}; 
Console.WriteLine(string.Join("\t", MyStringList));

Output of above code will return

1 2 3 4

Don’t get confuse Console does not print quotes of string. Now create a second variable MyNumberList as shown below

List<string> MyStringList = new List<string> {"1","2","3","4"}; 
Console.WriteLine(string.Join("\t", MyStringList));
List<int> MyNumberList = new List<int>();

Now if you want to convert my c# list with string to number then you can do

List<string> MyStringList = new List<string> {"1","2","3","4"}; 
List<int> MyNumberList = new List<int>();
MyNumberList = MyStringList.ConvertAll(int.Parse);
for (int i = 0; i < MyNumberList.Count; i++)

Once you run above then you can see output as shown below


This is a normal example for converting C# List with string to integer.

If you want to convert List with multiple objects with different data type then you can do

var target = MyOrginalList.ConvertAll(x => (DataTypeToChange)x);

Here, MyOriginalList is your original List variable. And DataTypeToChange is the data type in which you want your list to be converted.

But, if you use ConvertAll then you can not define target variable datatype. It will throw error.

To define data type of target variable then you can use

List<DataTypeToChange> target= new List<DataTypeToChange>(MyOrginalList.Cast<DataTypeToChange>());

Cast will match each and every property of your original list with your target list data type.

If you want to remove some properties from original list or you want some properties to be calculated based on your original list few properties then you can use

List<DataTypeToChange> target = MyOrginalList.Select(a => new DataTypeToChange() { TargetPropertyName = a.TargetPropertyName });

Here you can select properties from original list and then put in target list. These are the few methods that are use to convert List Data Type to Another List Data Type. For any type of other information contact here

You can start practicing here

Anil Mehra

I am Anil Mehra, a passionate, workaholic and a Full Stack Tech Savvy Programmer with true north towards growth. I have worked on 256 live projects in MNC. I am expertise in the field of Programming, Server Management, SEO, Blogging and SMO...

Leave a Reply

Your email address will not be published.

Back to top button