开发者

How to add data items to a List<Struct>

I have the following struct defined in a user control:

public struct ColumnData
{
    public string ColumnName { get; set; }
    public string ColumnDataItem { get; set; }
    public bool ColumnIsHyperLink { get; set; }
    public string ColumnHyperLinkURL { get; set; }
    public string ColumnHyperLinkPK { get; set; }
}

I create a new instance of List<ColumnData> (In a different code behind that creates an instance of the user control) and want to pass in values to it, but how do I assign them to specific attributes within the struct object?

I create an instance of the struct using the following code:

List<ColumnData> Da开发者_开发问答taItems = new List<ColumnData>();


This:

List<ColumnData> DataItems = new List<ColumnData>();

creates a new list.

This:

List<ColumnData> DataItems = new List<ColumnData>();
var cd = new ColumnData();
cd.ColumnName = "Taco";
DataItems.Add(cd);

creates a new list, a new struct, and adds an item to the list.


Change that to a class; all your woes relating to modifying struct properties (etc) will go away.

Alternatively, make it an immutable struct, and initialize it with the correct values at the point of creation - then the issue is moot, no matter how many times it is subsequently copied.

IMO the first is the right approach here.


so you need to do this:

public void AddToList(ColumnData columnData)
{
  DataItems.Add(columnData);
}

and call this method from your other class passing an already created and initialized columnData object.


List<ColumnData> DataItems = new List<ColumnData>();

Is creating the list that holds your structs not your structs itself.

You could use structs here for performance reasons (faster then classes).

 ColumnData data = new ColumnData
{
 ColumnName  = "Blaa"
};

DataItems.Add(data);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜