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.
Select(x => new TestClass() { AAA = (string)x[0], BBB = (string)x[1], CCC = (string)x[2] }). ToList();
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);
Generic List<T> is a generic collection in C#. The size can be dynamically increased using List, unlike Arrays.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With