假设我想要一份我附近所有地址的列表。如果朋友居住在任何地址,我还想将他们的姓名和电话号码关联起来。但并非每个地址都有一位朋友住在那里,因为许多地址都住着完全陌生的人,但相反,一个地址可能住着不止一个朋友。
总而言之,我需要一个地址列表,以及居住在这些地址的任何朋友的姓名/电话#对形式的所有这些字符串的关联。用于搜索此数据的索引只是地址,我不需要通过姓名或电话号码访问信息,但如果某个地址有朋友住在那里,我想迭代该数据。
在这种情况下使用的最佳 C# 数据结构是什么?您能否给我一些示例代码来显示它的实现?非常感谢。
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 implemented? Thanks much.
发布评论
评论(3)
词典课程是您最好的选择。我还将创建一个辅助类来存储名称/电话# 键值对,即使您可以使用本机 KeyValuePair 或 Tuple 类之一。最后,代码如下所示:
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:
您应该创建代表您的域的类型。
就像这样:
然后你在列表中进行操作。
You should create the types representing your domain.
Something like:
then you manipulate in lists.
您可能需要一个
ILookup
或一个Dictionary>
,它们基本上是同一件事。由于您想要包含所有地址,因此构造会比简单的ToDictionary
或ToLookup
稍微复杂一些,但这还不错:使用它非常简单:
You'll probably want an
ILookup<string, Friend>
or aDictionary<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 simpleToDictionary
orToLookup
, but it's not too bad:Using this is simple enough: