开发者

LINQ - Map string arrays to list of objects

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? Perha开发者_运维问答ps 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; }
}


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...

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:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜