我有一个包含一些值的List.
例:
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" });
Run Code Online (Sandbox Code Playgroud)
我有一个类似的课程
class TestClass
{
public string AAA {get;set;}
public string BBB {get;set;}
public string CCC {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
如何转换testData为类型List<TestClass>?
除此之外有没有办法转换?
testData.Select(x => new TestClass()
{
AAA = (string)x[0],
BBB = (string)x[1],
CCC = (string)x[2]
}).ToList();
Run Code Online (Sandbox Code Playgroud)
我不想提及列名,因此无论类更改如何,我都可以使用此代码.
我也有一个IEnumerable<Dictionary<string, object>>有数据.
您必须显式创建TestClass对象,而且还要将外部对象List<object>和内部对象强制转换为字符串.
testData.Cast<List<object>>().Select(x => new TestClass() {AAA = (string)x[0], BBB = (string)x[1], CCC = (string)x[2]}).ToList()
Run Code Online (Sandbox Code Playgroud)
您还可以在TestClass中创建一个构造函数,它可以List<object>为您执行脏操作:
public TestClass(List<object> l)
{
this.AAA = (string)l[0];
//...
}
Run Code Online (Sandbox Code Playgroud)
然后:
testData.Cast<List<object>>().Select(x => new TestClass(x)).ToList()
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
var res = testData
.Cast<List<object>>() // Cast objects inside the outer List<object>
.Select(list => new TestClass {
AAA = (string)list[0]
, BBB = (string)list[1]
, CCC = (string)list[2]
}).ToList();
Run Code Online (Sandbox Code Playgroud)
Linq是你的朋友:
var testList = testData
.OfType<List<object>>()
.Select(d=> new TestClass
{
AAA = d[0].ToString(),
BBB = d[1].ToString(),
CCC = d[2].ToString()})
.ToList();
Run Code Online (Sandbox Code Playgroud)
编辑:对于IEnumerable<Dictionary<string,object>>Linq语句中的,没有硬编码字段名称,我只需将每个Dictionary传递给要实例化的对象的构造函数,并让对象尝试使用它知道的字段名称来自我保湿:
var testList = testData
.OfType<Dictionary<string,object>>()
.Select(d=> new TestClass(d))
.ToList();
...
class TestClass
{
public TestClass(Dictionary<string,object> data)
{
if(!data.ContainsKey("AAA"))
throw new ArgumentException("Key for field AAA does not exist.");
AAA = data["AAA"].ToString();
if(!data.ContainsKey("BBB"))
throw new ArgumentException("Key for field BBB does not exist.");
BBB = data["BBB"].ToString();
if(!data.ContainsKey("CCC"))
throw new ArgumentException("Key for field CCC does not exist.");
CCC = data["CCC"].ToString();
}
public string AAA {get;set;}
public string BBB {get;set;}
public string CCC {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
构造函数可以使用反射循环来获取其类型的字段列表,然后从Dictionary中获取这些KVP并将它们设置为当前实例.这会使它变慢,但代码会更紧凑,如果TestClass实际上有十几个字段而不是三个字段,这可能是一个问题.基本思想保持不变; 提供将TestClass以您拥有的形式水合到TestClass所需的数据,并让类构造函数弄清楚如何处理它.理解这将在创建任何TestClass对象的第一个错误上抛出异常.
| 归档时间: |
|
| 查看次数: |
20382 次 |
| 最近记录: |