Wai Hieurn
Wai Hieurn

Reputation: 11

list of keyvaluepair to array in C#

I'm working on a Silverlight application. Since SL doesn't support arraylist, I'm making do with Arrays and List of objects. I want to convert a list of keyvaluepair to an array. But when I do the following:

private KeyValuePair<String, int>[] array1;
List<KeyValuePair<String, int>> list1 = methodCall.Result();
array1 = list1.ToArray();

I have debugged and confirmed that list1's results are not empty as a result of the method call. However, array1 is empty even after the conversion. What did I do wrong?

EDIT: here's the full code for code behind.

private KeyValuePair<String, int>[] array1;
private KeyValuePair<string, int>[] getlocalUniversities() 
{
    ASASService.ASASServiceClient client1 = new ASASService.ASASServiceClient();
    client1.getLocalUniversitiesCompleted += new EventHandler<ASASService.getLocalUniversitiesCompletedEventArgs>(client_getLocalUniversitiesCompleted);
    client1.getLocalUniversitiesAsync();
    return array1;
}
void client_getLocalUniversitiesCompleted(object sender, ASASService.getLocalUniversitiesCompletedEventArgs ex) 
{
    if (ex.Error == null && ex.Result != null)
    {
            List<KeyValuePair<string, int>> list1 = ex.Result;
            array1 = list1.ToArray();
    }
    else 
    {
        MessageBox.Show(ex.Error.Message);
    }
}

//

THE ASASService method getLocalUniversities() returns a List<KeyValuePair<String, int>>.
From there, I see that it has 1(expected) result consisting of <"NUS", 50>.
However, when I get it here as ex.Result, ex.Result contains 1 result consisting of <null, 0>.

Upvotes: 1

Views: 11658

Answers (1)

Stewart Sweet
Stewart Sweet

Reputation: 66

I think that you probably made a mistake when debugging. Assuming your Result() method is working fine, the code you listed should have worked. I ran this as a test and it worked fine.

KeyValuePair<string, int>[] array1;
List<KeyValuePair<string, int>> list1 = new List<KeyValuePair<string, int>>();
list1.Add(new KeyValuePair<string, int>("one", 1));
list1.Add(new KeyValuePair<string, int>("two", 2));
list1.Add(new KeyValuePair<string, int>("three", 3));
array1 = list1.ToArray();

Upvotes: 2

Related Questions