如何创建一个消除重复代码的函数

时间:2015-01-20 15:58:16

标签: c# asp.net arrays

我的Page_Load函数中包含以下代码:

string[] strArrayForEntity;
string[] strArrayForLocation;
string[] strArrayForSpecialty;
int inCounter;
inCounter = 0;

strArrayForEntity = new string[Entity.Items.Count];
foreach (ListItem li in Entity.Items)
{
    strArrayForEntity[inCounter] = li.Value;
    inCounter++;
}

inCounter = 0;
strArrayForLocation = new string[Location.Items.Count];
foreach (ListItem li in Location.Items)
{
    strArrayForLocation[inCounter] = li.Value;
    inCounter++;
}

inCounter = 0;
strArrayForSpecialty = new string[Specialty.Items.Count];
foreach (ListItem li in Specialty.Items)
{
    strArrayForSpecialty[inCounter] = li.Value;
    inCounter++;
}

正如您所看到的,除了数组名称和下拉列表ID之外,我正在重复相同的事情。

我想创建一个函数,我可以提供数组名称和下拉列表,所以我不必重复代码。我尝试了以下方法:

public void AddTooArray(string[] strArrayName, DropDownList strID)
{
    inCounter = 0;
    foreach (ListItem li in strID.Items)
    {
        strArrayName = li.Value;
        inCounter++;
    }
}

我打算这样称呼它:AddToArray(strArrayForEntity, Entity);

我收到此行中的错误:strArrayName = li.value; 错误:Cannot implicitly convert type 'string' to 'string[]'

我能解决这个问题吗?

测试代码:

protected void Page_Load(object sender, EventArgs e)
{
    strArrayForEntity = new string[Entity.Items.Count]; //count is 1 (2 entries in the dropdownlist)
    AddToArray(strArrayForEntity, Entity);
    MessageBox.Show(strArrayForEntity.Length.toString()); //displays 0
}
public void AddToArray(string[] strArrayName, DropDownList strID)
{
    inCounter = 0;
    foreach (ListItem li in strID.Items)
    {
        strArrayName[inCounter] = li.Value;
        inCounter++;
    }
}

2 个答案:

答案 0 :(得分:3)

您忘记了数组索引器。

strArrayName[inCounter] = li.Value;

答案 1 :(得分:2)

只需使用LINQ:

string[] strArrayForEntity = Entity.Items.Cast<ListItem>().Select(i => i.Value).ToArray();

请注意,ListItemCollection未实现IEnumerable<T>,因此您需要添加显式Cast<ListItem>()