dmuun
dmuun

Reputation: 1228

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? 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; }
}

Upvotes: 0

Views: 2697

Answers (2)

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59101

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.

Upvotes: 1

BoltClock
BoltClock

Reputation: 723428

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
    });
}

Upvotes: 4

Related Questions