Nitendra Jain
Nitendra Jain

Reputation: 499

Creating Dictionary from list

I want to prepare a dictionary from xml file nested with list because as have multiple values against one key. below code I am using for this -

  for (int i = 0; i < NumberOfVariation; i++)
    {
        SingleVariationDom.LoadXml(VariationSet[i].OuterXml);
        XmlNodeList CASInputParam = SingleVariationDom.GetElementsByTagName("CASInputParam");
        string Attr = null;
         ObjList.Clear();
        for (int j = 0; j < CASInputParam.Count; j++)
        {
            if (j == 0)
            {
                var NonTabularValueElement = SingleVariationDom.GetElementsByTagName("CASInputParam")[0];
                Attr = NonTabularValueElement.Attributes["MailParam"].Value;
            }
            else
            {
                var NonTabularValueElement = SingleVariationDom.GetElementsByTagName("CASInputParam")[j];
                string Attribut = NonTabularValueElement.Attributes["MailParam"].Value;
                ObjList.Add(Attribut);
            }
        }

        ObjParentDiction.Add(Attr, ObjList);

    }

When I am clearing the list object ObjList its clearing the values of dictionary in which I have already added values as a list.

Please suggest to avoid it.

Upvotes: 0

Views: 132

Answers (4)

Rashedul.Rubel
Rashedul.Rubel

Reputation: 3584

Create an instance of the list of object with
ObjList = new List() and ObjList.Clear() outside of the outerloop. 
then each time before entering the loop list of object will be cleared and 
after entering into the loop object will be repopulated again.

thanks.

Upvotes: 0

Rafal
Rafal

Reputation: 1091

You can replace:

ObjParentDiction.Add(Attr, ObjList);

to:

ObjParentDiction.Add(Attr, ObjList.ToList());

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

When I am clearing the list object ObjList its clearing the values of dictionary in which I have already added values as a list.

This is because you keep adding the same instance. Replace

  ObjList.Clear();

with

 ObjList = new List ...

to fix the problem.

Upvotes: 3

SLaks
SLaks

Reputation: 887315

ObjList is the same list in every iteration of the loop.

You want to create a different instance for each iteration by writing new List<string>().

Upvotes: 2

Related Questions