2011-05-17 43 views
7

什么是C#中的收集好来存储数据如下:好的C#集合

我已经检查在subjectId,varnumber,VARNAME,以及与每个复选框相关的标题带来的箱子。

我需要一个集合,可以是任意大小,像ArrayList中也许有可能:

 list[i][subjectid] = x; 
     list[i][varnumber] = x; 
     list[i][varname] = x; 
     list[i][title] = x; 

什么好的建议?

回答

14

A List<Mumble>其中Mumble是存储属性的小助手类。

List<Mumble> list = new List<Mumble>(); 
... 
var foo = new Mumble(subjectid); 
foo.varnumber = bar; 
... 
list.Add(foo); 
,.. 
list[i].varname = "something else"; 
+1

为嘟class类的帮助,见下面 – chris 2011-05-17 23:27:23

0

您可能想为此使用two-dimensional array,并为每个值分配阵列第二维中的位置。例如,list[i][0]将是subjectid,list[i][1]将是varnumber,依此类推。

+0

第一维可以增长还是缩小,还是必须提前分配特定的大小? – chris 2011-05-17 23:16:03

+4

Yuck。没有[幻数](http://en.wikipedia.org/wiki/Magic_number_(编程))。他们很难排除路上六个月的故障。 – 2011-05-17 23:17:54

+0

这不是一个很好的解决方案,因为这些索引是弱类型的。 (即你必须知道索引0是被忽略的)。 – Alan 2011-05-17 23:18:11

7
public Class MyFields 
{ 
    public int SubjectID { get; set; }   
    public int VarNumber { get; set; } 
    public string VarName { get; set; } 
    public string Title { get; set; } 
} 

var myList = new List<MyFields>(); 

要访问的成员:

var myVarName = myList[i].VarName; 
1

泛型列表,List<YourClass>将是巨大的 - 在YourClass有subjectid,varnumber等

0

的性质确定哪些集合,通常从你想用它做什么开始?

如果你的唯一标准是它可以anysize,那么我会考虑List<>

0

由于这是一个键,值对我会建议你使用一个通用的基于IDictionary收集。

// Create a new dictionary of strings, with string keys, 
// and access it through the IDictionary generic interface. 
IDictionary<string, string> openWith = 
    new Dictionary<string, string>(); 

// Add some elements to the dictionary. There are no 
// duplicate keys, but some of the values are duplicates. 
openWith.Add("txt", "notepad.exe"); 
openWith.Add("bmp", "paint.exe"); 
openWith.Add("dib", "paint.exe"); 
openWith.Add("rtf", "wordpad.exe"); 
+0

字典将不会工作,因为主观,varnumbers都绑在一起作为一个独特的主键,所以你不能有相同的主题字典字典dictSubject(这就是问题我有) – chris 2011-05-17 23:19:58

+0

我通常使用汉斯方法,因为它允许你强烈地键入整个集合,所以这可能是最好的选择。然后你可以使用枚举来表示键。 – 2011-05-17 23:22:10

0

正如其他人所说,那样子你会更好,创建一个类,使您的列表返回一个包含所有你需要的数据的对象来保存值。虽然二维数组可能很有用,但这看起来不像这些情况之一。

有关更好的解决方案,为什么在这种情况下二维数组/列表可能不是你所想读一个好主意,了解更多信息:Create a list of objects instead of many lists of values

0

如果有外部机会的[i]顺序是不是在可预知的顺序,或可能有差距,但你需要使用它作为一个重点:

public class Thing 
{ 
    int SubjectID { get; set; }   
    int VarNumber { get; set; } 
    string VarName { get; set; } 
    string Title { get; set; } 
} 

Dictionary<int, Thing> things = new Dictionary<int, Thing>(); 
dict.Add(i, thing); 

然后找到一个Thing

var myThing = things[i];