【发布时间】:2021-10-19 07:01:00
【问题描述】:
我有两个不同的类:Employee 和 Customer。每个都有两个共同的属性:名称和地址。有没有办法不使用 List 直接将字符串转换为对象数组?
private static List<Employee> NewMethod1(string strArr)
{
List<Employee> lst = new List<Employee>();
if (strArr !=null)
{
strArr.Split(',').ToList().ForEach(x => lst.Add(new Employee() { Name = x }));
}
return lst.ToArray();
}
或者使这行代码足够通用,以便我可以使用内联代码?
strArr.Split(',').ToList().ForEach(x => lst.Add(new Employee() { Name = x }));
【问题讨论】:
-
strArr.Split(',').Select(x => new Employee() {...}).ToList()? -
哇!!伟大的!!这真的很有帮助。
-
@canton7 如果您将其发布为答案,我会接受,否则我会接受 4lexKislitsyn 的答案。你是第一个,我想先把这个荣誉给你。
-
@4lex 的回答非常好:接受这个