Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Generic List to specific type

Tags:

c#

.net

I have a List which contains some values.

Example:

List<object> testData = new List <object>();
testData.Add(new List<object> { "aaa", "bbb", "ccc" });
testData.Add(new List<object> { "ddd", "eee", "fff" });
testData.Add(new List<object> { "ggg", "hhh", "iii" });

And I have a class like

class TestClass
{
    public string AAA {get;set;}
    public string BBB {get;set;}
    public string CCC {get;set;}
}

How to convert the testData to the type List<TestClass> ?

Is there a way to convert other than this?

testData.Select(x => new TestClass()
{
   AAA = (string)x[0],
   BBB = (string)x[1],
   CCC = (string)x[2]
}).ToList();

I don't want to mention the column names, so that I can use this code irrespective of class changes.

I also have a IEnumerable<Dictionary<string, object>> which has the data.

like image 756
Ramesh Durai Avatar asked Sep 14 '12 14:09

Ramesh Durai


People also ask

How to convert generic List to specific type in C#?

Select(x => new TestClass() { AAA = (string)x[0], BBB = (string)x[1], CCC = (string)x[2] }). ToList();

Can we convert list to object?

A list can be converted to a set object using Set constructor. The resultant set will eliminate any duplicate entry present in the list and will contains only the unique values. Set<String> set = new HashSet<>(list);

What is generic list in C#?

Generic List<T> is a generic collection in C#. The size can be dynamically increased using List, unlike Arrays.

How do you know if a type is generic?

To examine a generic type and its type parametersGet an instance of Type that represents the generic type. In the following code, the type is obtained using the C# typeof operator ( GetType in Visual Basic, typeid in Visual C++). See the Type class topic for other ways to get a Type object.


1 Answers

You have to explicitly create the TestClass objects, and moreover cast the outer objects to List<object> and the inner objects to strings.

testData.Cast<List<object>>().Select(x => new TestClass() {AAA = (string)x[0], BBB = (string)x[1], CCC = (string)x[2]}).ToList()

You could also create a constructor in TestClass that takes List<object> and does the dirty work for you:

public TestClass(List<object> l)
{
    this.AAA = (string)l[0];
    //...
}

Then:

testData.Cast<List<object>>().Select(x => new TestClass(x)).ToList()
like image 158
lc. Avatar answered Oct 12 '22 23:10

lc.