简体   繁体   English

LINQ - Map 字符串 arrays 到对象列表

[英]LINQ - Map string arrays to list of objects

How do I map string arrays to a list of objects?如何将 map 字符串 arrays 到对象列表? A for loop would do it but wondering if there's a more elegant way to do this?一个 for 循环可以做到这一点,但想知道是否有更优雅的方式来做到这一点? Perhaps with Linq?也许与 Linq?

String arrays:字符串 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; }
}

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...假设您已确保所有 arrays (所有这些,而不仅仅是您问题中的前三个)大小完全相同且顺序正确(因此所有值都将对应于正确的Contact对象),一个 for 循环就足够了...

var contactList = new List<Contact>();

for (int i = 0; i < names.Length; i++)
{
    contactList.Add(new Contact
    {
        Name = names[i], 
        Company = companies[i], 
        Affiliation = affiliations[i],
        // etc
    });
}

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:相反,直接初始化一个Contact列表:

var contacts = new List<Contact>()
{
    new Contact()
    {
        Name = "john",
        Company = "company ABC",
        Affiliation = "affiliation 1",
    },
    new Contact()
    {
        // ...
    },
    // ...
};

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.如果您的列表大小不匹配,或者其中一个条目没有一些数据,这更具可读性,并且不易出错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM