A Good C# Collection
What's a good collection in C# to store the data below:
I have check boxes that bring in a subjectId, varnumber, varname, and title associated with each checkbox.
I need a collection that can be any size, something like ArrayList maybe with maybe:
list[i][subjectid] = x;
list[i][varnumber] = x;
list[i][varname] = x;
list[i][title] = x;
Any good ideas?开发者_如何学C
A List<Mumble>
where Mumble is a little helper class that stores the properties.
List<Mumble> list = new List<Mumble>();
...
var foo = new Mumble(subjectid);
foo.varnumber = bar;
...
list.Add(foo);
,..
list[i].varname = "something else";
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>();
To access a member:
var myVarName = myList[i].VarName;
A generic list, List<YourClass>
would be great - where YourClass has properties of subjectid, varnumber etc.
You'd likely want to use a two-dimensional array for this, and allocate positions in the second dimension of the array for each of your values. For instance, list[i][0]
would be the subjectid
, list[i][1]
would be varnumber
, and so on.
Determining what collection, typically begins with what do you want to do with it?
If your only criteria is it can be anysize, then I would consider List<>
Since this is a Key, Value pair I would recommend you use a generic IDictionary based collection.
// 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");
As others have said, it looks like you'd be better creating a class to hold the values so that your list returns an object that contains all the data you need. While two-dimensional arrays can be useful, this doesn't look like one of those situations.
For more information about a better solution and why a two-dimensional array/list in this instance isn't a good idea you might want to read: Create a list of objects instead of many lists of values
If there's an outside chance that the order of [i]
is not in a predictable order, or possibly has gaps, but you need to use it as a key:
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);
Then to find a Thing
:
var myThing = things[i];
精彩评论