user149169
user149169

Reputation: 77

c#, lambda expressions, where is the error?

I have this method

    public static List<Contact> Load(string filename)
    {
        if (!File.Exists(filename))
        {
            throw new FileNotFoundException("Data file could not be found", filename);

        }
        var contacts = 
            System.Xml.Linq.XDocument.Load(filename).Root.Elements("Contact").Select
            (
                x => new Contact() { //errors out here, XXXXXX
                            FirstName = (string)x.Element("FirstName"),
                            LastName = (string)x.Element("LastName"),
                            Email = (string)x.Element("Email")
                         }
            );
        return contacts.ToList();// is this line correct?, it should return List...
    }

I have Contacts.xml with Contact elements in it.

<Contacts>
    <Contact>
        <FirstName>Mike</FirstName>
        <LastName>Phipps</LastName>
        <Email>[email protected]</Email>
    </Contact>
    <Contact>
        <FirstName>Holly</FirstName>
        <LastName>Holt</LastName>
        <Email>[email protected]</Email>
    </Contact>
    <Contact>
        <FirstName>Liz</FirstName>
        <LastName>Keyser</LastName>
    </Contact>
</Contacts>

I have a contact.cs with this code

public class Contact
{
    public Contact(string firstName, string lastName, string email)
    {
        FirstName = firstName;
        LastName = lastName;
        Email = email;
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public string Address { get; set; }
}

on the line, where stamped with 'XXXXXX', how should i change the line to make it work?

Upvotes: 0

Views: 236

Answers (2)

LukeH
LukeH

Reputation: 269368

The constructor of your Contact class requires three arguments - firstName, lastName and email - but you're attempting to call the constructor with no arguments and then trying to set the properties using object initializer syntax.

To fix it you need to pass the three arguments into the constructor itself:

x => new Contact(
    (string)x.Element("FirstName"),
    (string)x.Element("LastName"),
    (string)x.Element("Email"));

Upvotes: 8

Yvo
Yvo

Reputation: 19263

I think you're missing a public constructor in Contact.

public class Contact
{
    public Contact() {}

    public Contact(string firstName, string lastName, string email) {
        FirstName = firstName;
        LastName = lastName;
        Email = email;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public string Address { get; set; }
}

Or just use the existing constructor.

Upvotes: 0

Related Questions