一个很好的C#系列

时间:2011-05-17 23:10:51

标签: c# .net arrays collections

C#中用于存储以下数据的好集合是什么:

我的复选框带有与每个复选框相关联的subjectId,varnumber,varname和title。

我需要一个可以是任何大小的集合,类似于ArrayList,也许可能是:

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

有什么好主意吗?

8 个答案:

答案 0 :(得分: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 :(得分: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;

答案 2 :(得分:1)

通用列表List<YourClass>会很棒 - 其中YourClass具有subjectid,varnumber等属性。

答案 3 :(得分:0)

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

答案 4 :(得分:0)

确定什么样的集合,通常从你想用它做什么开始?

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

答案 5 :(得分:0)

由于这是一个Key,Value对,我建议您使用基于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");

答案 6 :(得分:0)

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

有关更好的解决方案的更多信息以及为什么这个实例中的二维数组/列表不是一个好主意,您可能需要阅读:Create a list of objects instead of many lists of values

答案 7 :(得分: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];