将通用列表转换为特定类型
我有一个包含一些值的List。
例:
List testData = new List (); testData.Add(new List { "aaa", "bbb", "ccc" }); testData.Add(new List { "ddd", "eee", "fff" }); testData.Add(new List { "ggg", "hhh", "iii" });
我有一个类似的课程
class TestClass { public string AAA {get;set;} public string BBB {get;set;} public string CCC {get;set;} }
如何将testData
转换为List
类型?
除此之外有没有办法转换?
testData.Select(x => new TestClass() { AAA = (string)x[0], BBB = (string)x[1], CCC = (string)x[2] }).ToList();
我不想提及列名,因此无论类更改如何,我都可以使用此代码。
我还有一个IEnumerable<Dictionary>
,它有数据。
您必须显式创建TestClass对象,而且将外部对象强制转换为List
,将内部对象强制转换为字符串。
testData.Cast>().Select(x => new TestClass() {AAA = (string)x[0], BBB = (string)x[1], CCC = (string)x[2]}).ToList()
您还可以在TestClass中创建一个构造函数,它接受List
并为您执行脏工作:
public TestClass(List
然后:
testData.Cast>().Select(x => new TestClass(x)).ToList()
你可以这样做:
var res = testData .Cast>() // Cast objects inside the outer List
Linq是你的朋友:
var testList = testData .OfType>() .Select(d=> new TestClass { AAA = d[0].ToString(), BBB = d[1].ToString(), CCC = d[2].ToString()}) .ToList();
编辑:对于IEnumerable
,并且在Linq语句中没有硬编码字段名称,我只需将每个Dictionary传递给要实例化的对象的构造函数,并让对象尝试自我保湿使用它知道的字段名称:
var testList = testData .OfType>() .Select(d=> new TestClass(d)) .ToList(); ... class TestClass { public TestClass(Dictionary 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;} }
构造函数可以使用reflection循环来获取其类型的字段列表,然后将这些KVP从Dictionary中取出并将它们设置为当前实例。 这会使它变慢,但代码会更紧凑,如果TestClass实际上有十几个字段而不是三个字段,这可能是一个问题。 基本思想保持不变; 提供将TestClass以您拥有的forms水合到TestClass所需的数据,并让类构造函数弄清楚如何处理它。 理解这会在创建任何TestClass对象的第一个错误上抛出exception。