LINQ - 将字符串数组映射到对象列表
如何将字符串数组映射到对象列表? for 循环可以做到这一点,但想知道是否有更优雅的方法来做到这一点?也许与 Linq 一起?
字符串数组:
string[] names = { "john","jane"};
string[] companies = { "company ABC", "" };
string[] affiliations = { "affiliation 1", "affiliation 2" };
联系方式:
public class Contact
{
public string Name { get; set; }
public string Company { get; set; }
public string Affiliation { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
}
How do I map string arrays to a list of objects? A for loop would do it but wondering if there's a more elegant way to do this? Perhaps with Linq?
String arrays:
string[] names = { "john","jane"};
string[] companies = { "company ABC", "" };
string[] affiliations = { "affiliation 1", "affiliation 2" };
Contact:
public class Contact
{
public string Name { get; set; }
public string Company { get; set; }
public string Affiliation { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您已确保所有数组(所有,而不仅仅是问题中的前三个)的大小完全相同且顺序正确(因此所有值都将对应于正确的值)
Contact
对象),一个 for 循环就足够了......Assuming you've ensured all of the arrays (all of them, not just the first three in your question) are exactly the same size and in the right order (so all the values will correspond to the right
Contact
objects), a for loop will suffice...如果您的代码中确实有这两个定义,那么您应该完全跳过字符串数组步骤。相反,直接初始化
Contact
列表:这更具可读性,并且不易出错,以防您的列表大小不匹配,或者没有某个条目的某些数据。
If you truly have both those definitions in your code, then you should just skip the string array step entirely. Instead, initialize a list of
Contact
directly:This is more readable, and is less error prone, in case you have mis-matched list sizes, or don't have some data for one of the entries.