简体   繁体   English

有效的C#2D列表

[英]Effective C# 2D lists

I am creating a State-Manager for a program. 我正在为一个程序创建一个State-Manager。 Each state will have a ID and a State class. 每个州都有一个ID和一个州级。 I can add as many stats as I want by using an Add() function. 我可以使用Add()函数添加任意数量的统计数据。 Using a Change(ID) function will get change the state to the one in the list with a matching ID. 使用更改(ID)功能将使用匹配的ID将状态更改为列表中的状态。 Then ander further calls to the Manager will refer to the set state. 然后,ander进一步调用Manager将引用设置状态。

I would like to create a 2D list as such: 我想创建一个2D列表:

//short = ID No, IState = Sate Interface all states are based on
List<short, IState> StateList = new List<short, IState>();

I think for C# I'd require to create a List of Lists to get a 2D but I am unsure as the Intellisense marks it as List < T > with T being the param. 我认为对于C#我需要创建一个列表列表以获得2D,但我不确定,因为Intellisense将其标记为List <T>,其中T为param。 Is there a better way of doing this? 有没有更好的方法呢? I appologise if this is very basic as I'm very new to this whole List idea. 如果这是非常基本的,我会道歉,因为我对整个列表的想法都很新。

Simply replace List with Dictionary . 只需将List替换为Dictionary You want a key/value pair as your list item, which a Dictionary provides. 您需要一个键/值对作为列表项,这是Dictionary提供的。

Dictionary<short, IState> StateList = new Dictionary<short, IState>();

You can then index into the dictionary to find the state you want: 然后,您可以索引到字典中以查找所需的状态:

// Retrieve State 5
var state5 = StateList[5];

Can you use a Dictionary object? 你可以使用Dictionary对象吗? These are great for name/value pairs. 这些非常适合名称/值对。

You could implement it as 你可以实现它

Dictionary<short, IState> StateList = new Dictionary<short, IState>();

then just do 然后就做

StateList.Add(1, new State() { blah, blah });

You can create a List<Tuple<short, IState>> if you want. 如果需要,您可以创建List<Tuple<short, IState>>

However, if the order of the items in the list is not important to you, you can use a Dictionary<short, IState> . 但是,如果列表中项目的顺序对您不重要,则可以使用Dictionary<short, IState>

If the order is important, but happens to be the ID (lower IDs come before higher IDs, for instance), you can use a SortedDictionary<short, IState> . 如果订单很重要,但恰好是ID(例如,较低的ID位于较高的ID之前),则可以使用SortedDictionary<short, IState>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM