开发者

What C# data structure should I use to map a varying number of key/value pairs to a list of strings?

开发者 https://www.devze.com 2023-02-11 11:05 出处:网络
Let\'s say I want a list of all the addresses in my neighborhood. And I also want to associate a friend\'s name and phone number if they live at any of the addresses. But not every address has a frien

Let's say I want a list of all the addresses in my neighborhood. And I also want to associate a friend's name and phone number if they live at any of the addresses. But not every address has a friend living there, as complete strangers live at many of the addresses, but conversely more than one friend may live at a single address.

To summarize, I need both a list of addresses, as well as associations to all of those strings in the form of a name/phone# pair for any friends who live at those addresses. The index for searching on this data is only the address, I don't need to access the info by name or by phone number, but I would like to iterate through that data if an address has friends living there.

What is the best C# data structure to use in this situation, and could you perhaps give me some sample code showing it im开发者_如何学Pythonplemented? Thanks much.


The Dictionary class is your best choice. I'd also create a helper class for storing the Name/Phone # key-value pairs, even though you can use one of the native KeyValuePair or Tuple classes. In the end, code would look like this:

class ContactInfo
{
   string Name;
   string TelephoneNumber;
}

Dictionary<string, ICollection<ContactInfo>> addressAndPeopleLivingThere = 
    new Dictionary<string, ICollection<ContactInfo>>();

addressAndPeopleLivingThere.Add("1 Some Street", new List<ContactInfo>());
addressAndPeopleLivingThere["1 Some Street"].Add(new ContactInfo { Name = "Name", TelephoneNumber = "000-000-0000" });


You should create the types representing your domain. Something like:

public class Address{
  public string StreetName{get;set;}
  public List<Person> Friends{get;set;}
}
public class Person{
   public string Name{get;set;}
   public string Phone{get;set;}
}

then you manipulate in lists.

List<Address> addresses = new List<Address>;

    var addWithFriends = from c in addresses where c.Count > 0 select c;


You'll probably want an ILookup<string, Friend> or a Dictionary<string, IEnumerable<Friend>>, which basically amounts to the same thing. Since you want to include all the addresses, construction will be a little more complicated than a simple ToDictionary or ToLookup, but it's not too bad:

var friendsByAddress = friends.ToLookup(f => f.Address);
var addressesWithFriends = addresses.ToDictionary(
    a => a,
    a => !friendsByAddress.Contains(a) ? Enumerable.Empty<Friend>() : friendsByAddress[a]);

Using this is simple enough:

var friendsAtAddress = addressesWithFriends[address];
foreach(var friend in friends) 
{
    ...
}
0

精彩评论

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