Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have three classes: person, address and phone. A person can have multiple addresses and each address has phone numbers. Here how to initialize and assign values multiple address and phone number. Below is my class model.

C#
public class Person
{
    public string Name { get; set; }
    public string dob { get; set; }
    public List<Address> address { get; set; }
    public Person()
    {
        this.address = new List<Address>();
    }
}

public class Address
{
    public string street { get; set; }
    public string city { get; set; }
    public string pobox { get; set; }
    public string postalcode { get; set; }
    public Phone phone { get; set; }
    public Address()
    {
        this.phone = new Phone();
    }
}

public class Phone
{
    public string Mobile { get; set; }
    public string Landline { get; set; }
}
Posted
Updated 28-Oct-15 21:06pm
v2
Comments
Ralf Meier 29-Oct-15 2:11am    
... and a Person also could have multiple Phonenumbers - not depending on any adress.

But now : what is your question ?
BillWoodruff 29-Oct-15 3:01am    
Why did you tag your post: XmlSerializer ?

What's wrong with the code now: errors ? incomplete ?

Quote:
how to initialize and assign values multiple address and phone number.
There are several ways you can initialize/assign to whatever Collection data-structure you select to hold the multiple values. Here's an example that reflects the way I like to work:
C#
public enum PhoneType
{
    Other,
    Home, Mobile
}

public enum AddressType
{
    Other,
    Home, Office, PO_Box
}

public class Person
{
    public string Name { get; set; }

    // see note on Constructor below
    public DateTime? Dob { get; set; }

    public Dictionary<PhoneType, List<int>> Phones { get; set; }
    public Dictionary<AddressType, List<Address>> Addresses { get; set; }

    public Person(string name,
        // use of nullable DateTime is a work-around
        // for the fact that a DateTime in a parameter
        // list must be a compile-time Constant
        DateTime? dob,

        // note the use of optional parameters here
        Dictionary<PhoneType, List<int>> phones = null,
        Dictionary<AddressType, List<Address>> addresses = null

        )
    {
        Name = name;
        // note use of null-coalsescing operator here
        Dob = dob ?? DateTime.MinValue;
        Phones = phones ?? new Dictionary<PhoneType, List<int>>();
        Addresses = addresses ?? new Dictionary<AddressType, List<Address>>();
    }

    public void AddPhone(PhoneType ptype , int number)
    {
        // requires Linq

        if(Phones == null) Phones = new Dictionary<PhoneType, List<int>>();

        // new type of Phone ? initialize with new List<int>
        if(! Phones.ContainsKey(ptype)) Phones.Add(ptype, new List<int>());
        
        // note: no check for duplicates here : implement check ?
        Phones[ptype].Add(number);
    }

    public void AddPhones(PhoneType ptype, List<int> phones)
    {
        if (Phones == null) Phones = new Dictionary<PhoneType, List<int>>();

        // new type of Phone ? initialize with new List<int>
        if (!Phones.ContainsKey(ptype)) Phones.Add(ptype, new List<int>());
        
        Phones[ptype].AddRange(phones);
    }

    public void RemovePhone(PhoneType ptype, int number)
    {
        // requires Linq

        var numbersbykey = Phones.FirstOrDefault(kvp => kvp.Key == ptype);

        if (numbersbykey.Value != null && numbersbykey.Value.Contains(number)) numbersbykey.Value.Remove(number);
    }

    //public void AddAddress(AddressType atype, string street, string city, string postalCode)
    //{
    //     // you write the code for this
    //}

    //public void RemoveAddress(AddressType atype, ???)
    //{
    //    // you write the code for this
    //}
}
Notes:

1. I like using Enums since they both help document the code and are easily expanded/altered in the future

2. I like using Dictionaries with Enum values as Keys when each Key will store multiple values

3. I like writing explicit Add methods for adding one, or many, values to a collection. Keeps the Constructor uncluttered when there may be many variables/parameters.
 
Share this answer
 
v4
Comments
Maciej Los 30-Oct-15 3:36am    
Bill, take a while and look at your code.
BTW: +5!
BillWoodruff 30-Oct-15 4:33am    
Thanks, Maciej, I re-pasted in the code, and it looks okay now. The strange this is that the first time I pasted in the code, it looked formatted properly after I posted the message ... but, obviously, it ended up trashed.
Maciej Los 30-Oct-15 4:44am    
Now, you know why i wasn't able to explain what is wrong.
Cheers,
Maciej
Here is my advice: through out this problematic XmlSerialize. Use much better Data Contract with DataContractSerialize — much easier to use, fully non-intrusive and data-agnostic, can work with arbitrary data model, not necessarily a tree, and so on. Please see:
http://msdn.microsoft.com/en-us/library/ms733127.aspx[^],
https://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer%28v=vs.110%29.aspx[^].

See also my past answers:
how to pass a datacontract from a C#/WCF code to Managed C++[^],
How can I utilize XML File streamwriter and reader in my form application?[^],
Creating property files...[^],
deserializing list<class object> cause the objects property lose their reference to the objects of the base class[^].

—SA
 
Share this answer
 
Comments
sunsuhesh 29-Oct-15 2:44am    
Thanks Sergey, Actually i need to use it for web service , and i need to serialize with message contract because my output should be serialized with header and body.
Sergey Alexandrovich Kryukov 29-Oct-15 3:00am    
Not sure. Data Contract was developed primarily for the use in WCF services, but also anywhere else.
—SA
BillWoodruff 29-Oct-15 3:04am    
Edit your original post so this information is in it.
BillWoodruff 29-Oct-15 13:59pm    
Voted #5 to counteract unwarranted down-vote. The OP tagged the question XMLSerialize and this information is relevant.
phil.o 30-Oct-15 3:15am    
5'd. Don't know why it had been downvoted.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900