存储数据字段集合并通过标识符检索
在 C# 中,如何存储值的集合,以便以后如果我想检索特定值,我可以执行以下操作:
myCollection["Area1"].AreaCount = 50;
或
count = myCollection["Area1"].AreaCount;
通用列表?
我想将多个属性存储到一把“钥匙”中。课程是答案吗?
In C#, how can I store a collection of values so if I want to retrieve a particular value later, I can do something like:
myCollection["Area1"].AreaCount = 50;
or
count = myCollection["Area1"].AreaCount;
Generic list?
I'd like to store more than one property to a "key". Is a class the answer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在寻找
Dictionary
类。 (其中YourClass
有一个AreaCount
属性)You're looking for the
Dictionary<string, YourClass>
class. (WhereYourClass
has anAreaCount
property)编辑
根据您的评论,您似乎想要一个字典(如已经建议的那样),其中您的对象保存所有“值”。
例如:
或者,您可以向您的类添加一个
string
“Name”(我使用字段作为示例,您可能会使用属性)并使用 Linq:这有更多帮助吗?
原始回复
我不完全确定你在问什么,但我会先给出。
给定一个对象列表,您需要从中获取特定对象,(通常)有 4 种方法 - 根据您的具体需求。
如果您的对象已经支持某种搜索(例如 String.Contains()),通用
List
确实只能很好地做到这一点。SortedList 使用 IComparer 对 Key 值进行比较和排序,并排列就这样列出来。
字典 存储键和值,以便
KeyValuePair< /code> 可以检索对象。
HashTable 使用键和键必须实现
GetHashCode()
和ObjectEquals
的值您需要的具体值将根据您的具体要求而有所不同。
EDIT
Based on your comment, it seems like you want a Dictionary (as already suggested) where your object holds all your 'values.'
For Instance:
Alternatively, you could add a
string
"Name" to you class (I'm using fields for the example, you'd probably use properties) and use Linq:Does that help more?
ORIGINAL RESPONSE
I'm not completely sure what you're asking, but I'll give it ago.
Given a list of Objects from which you need to grab a particular object, there are (generally) 4 ways- depending on your specific needs.
The Generic
List<T>
really only does this well at all if your object already supports some kind of searching (like String.Contains()).A SortedList uses IComparer to compare and sort the Key values and arrange the list that way.
A Dictionary stores a Key and Value so that
KeyValuePair
objects can be retrieved.A HashTable uses Keys and Values where the Keys must implement
GetHashCode()
andObjectEquals
The specific one you need will vary based on your specific requirements.
此功能由索引器提供
This functionality is provided by indexers