Click here to Skip to main content
15,915,867 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I am not able to add key and value in List keyvaluepair during runtime. it's overwritting again and again. where i'm doing wrong please correct me.

C#
 List<KeyValuePair<string, string>>

foreach (XmlNode xn in xmlLabelList)
{

     string propert = xn[&quot;name&quot;].InnerText;
              
     string label = xn[&quot;label&quot;].InnerText;
              
     kvpList = new List<KeyValuePair<string, string>>();
     kvpList.Add(KeyValuePair<string,string>(propert, label));

}


What I have tried:

here property and label have some value. that is coming from xml. both should be add in List keyvaluepair
Posted
Updated 24-May-16 4:19am
v2
Comments
Sergey Alexandrovich Kryukov 24-May-16 10:21am    
Why would you have a list of the element of this element type? You can, but why? This type is designed to work with associative containers, such as Dictionary, SortedDictionary, SortedList.
—SA

1 solution

try this
Dont create the instance of the list inside the loop.

C#
List<KeyValuePair<string, string>> kvpList = new List<KeyValuePair<string, string>>();
         foreach (XmlNode xn in xmlLabelList)
         {
             string propert = xn["name"].InnerText;
             string label = xn["label"].InnerText;
             kvpList.Add(new KeyValuePair<string,string>(propert, label));

         }
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 24-May-16 10:24am    
My 5, but see also my comment to the question.
Also, hard-coding of "name" and "label" is hardly acceptable.
—SA
Karthik_Mahalingam 24-May-16 10:28am    
Thanks Sergey,
Yes, he could have chosen dictionary, but to avoid the duplicate key exceptions he might be using List. who knows :)
Sergey Alexandrovich Kryukov 24-May-16 10:31am    
How? It's the associative containers and sets are designed to avoid duplicate keys; in lists, the mechanism is meaningless. Manual checkup for uniqueness defeats the purpose and is bad in performance.
—SA
Karthik_Mahalingam 24-May-16 10:33am    
may be he is not aware of dictionary type.
Sergey Alexandrovich Kryukov 24-May-16 10:37am    
It's not only the dictionary type, and not about awareness of the existence of some times. That's why I raise the issue. It would be a good idea review all types in System.Collections.Generic and at least understand their purpose, before designing any code.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900