How to create a function which eliminates repeated code

SearchForKnowledge

I have the following code in my Page_Load function:

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++;
}

As you can see I am repeating the same thing with the exception of the array name and the dropdownlist ID.

I wanted to make a function where I can feed the array name and the dropdownlist so I don't have to have repeated code. I tried the following:

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

I was planning on calling it like this: AddToArray(strArrayForEntity, Entity);

I am getting the error in this line: strArrayName = li.value; Error: Cannot implicitly convert type 'string' to 'string[]'

Can I resolve the issue?

Test code:

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++;
    }
}
Sergey Kolodiy

Just use LINQ:

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

Notice that ListItemCollection does not implement IEnumerable<T>, so you need to add explicit Cast<ListItem>().

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive