Wednesday 2 May 2012

Beginning .Net , C# Tips : Convert List of Object's Value to List of Integer in C# Programming

There are many situations where you want to convert List<Object>'s Value to List<int>.
Using Linq Method ConvertAll we can achieve in one sentence.
LINQ Namespace is System.Linq

Here are sample Example For this:

C# Example :
List<Object> obj = new List<Object>();
obj.Add("1");
obj.Add("2");
obj.Add("3");
List<int> objInt = obj.ConvertAll<int>(delegate(Object o) { return Convert.ToInt32(o.ToString()); });


Here convert object's value to integer.
There are situations where you get value in form of object's list and you want to convert that.

VB.net Example :
Dim obj As New List(Of [Object])()
obj.Add("1")
obj.Add("2")
obj.Add("3")
Dim objInt As List(Of Integer) = obj.ConvertAll(Of Integer)(Function(o As Object) Convert.ToInt32(o.ToString()))

No comments:

Post a Comment