在 C# 中创建两种数据类型的可搜索列表
从 C# 类中开始数据结构,尝试创建一个字符串和一个 int 一起引用的可搜索数组列表(名称和数字)。我需要能够搜索名称,并检索名称和它所附加的数字。有人告诉我可以使用结构的数组列表,但从未使用过结构。有什么简单的解释,或者更好的方法吗?
先感谢您。
Taking beginning Data Structures in C# class, trying to make a searchable arraylist of a string and an int referenced together (name and number).I need to be able to search for the name, and retrieve both the name and the number it's attached to. I was told I can use an arraylist of structs, but have never used structs. Any simple explanation how, or a better way?
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能应该使用类似散列的东西,因为结构的 ArrayList 是一个有点方钉圆孔。
您可以像声明类一样声明结构。
您可以像使用任何类型一样创建一个数组列表。
这里的另一个问题是 ArrayList 不是通用的,它会将所有内容转换为 Object,这意味着您必须将所有内容转换回类型
Foo
才能使用它。如果您必须使用像
List
这样的通用列表类并声明其类型,走 List 而不是 Hash 的路线,那么您的情况会好得多;至于搜索列表,我更喜欢使用
LINQ
方法,因为它们编码速度快且易于阅读。但如果你做不到这一点,那么迭代总是有效的
You should probably be using something like a hash for this as an
ArrayList
of structs is a bit square peg round hole.You declare a struct just like a calss.
And you can make an array list of then as you would with any type
The other issue here is that
ArrayList
isn't generic, it will cast everything toObject
which means you will have to cast everything back to typeFoo
to work with it.You would be much better off, if you have to go the route of List instead of Hash using a generic list class like
List
and declaring its type;As for searching a list, I prefer to use the
LINQ
methods, because they are quick to code and easy to read.But if you cannot do that then iteration always works