Click here to Skip to main content
15,897,181 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
C#
var result = from d in data
                         select new Dictionary<string, string>()
             {
                { "Name", (string)d.Attribute("Name") },
                 { "MappedName", (string)d.Attribute("MappedName") },
                 { "DataType", (string)d.Attribute("DataType") },
                 { "length", (string)d.Attribute("length") }

             };

            foreach (var item in result)
            {
                foreach (var y in item)
                {
                    hash.Add(y.Key, y.Value);
                }
            }



getting error as :An item with the same key has already been added.

my xml doc:

XML
<ColumnNames>
<Column Name="RequestDate" MappedName="@A" DataType="Datetime" length="" />
<Column Name="AgentNumber" MappedName="@B" DataType="varchar"  length="4" />
</ColumnNames>
Posted
Updated 6-Aug-13 20:56pm
v2
Comments
Naz_Firdouse 7-Aug-13 2:51am    
there may exists duplicate Name attributes in your data...
verify that else assign a value as a key which is unique in your collection
Sergey Alexandrovich Kryukov 7-Aug-13 2:52am    
What is unclear in this message? Do you understand that the keys in key-indexed (associative) containers should be unique?
Also, pat attention that the dictionary with values identical to keys makes no sense at all. You should use HashSet then.
—SA

The exception is thrown in this line:
C#
hash.Add(y.Key, y.Value);

if y.Key is a value already existing in the (unique) Key collection of your Hashtable, it will of course throw that exception.

It is your duty to make sure that you insert a value which is unique OR reconsider you application specification, (e.g. using other data structures that allow duplicates etc)

Good luck,
Edo
 
Share this answer
 
v2
The error simply means that because your dictionaries all look like this:

{ "Name", (string)d.Attribute("Name") },
                 { "MappedName", (string)d.Attribute("MappedName") },
                 { "DataType", (string)d.Attribute("DataType") },
                 { "length", (string)d.Attribute("length") }

When you adding them to the hashtable the keys it tries to use are:

Name, MappedName, DataType, Length

Once it has added the first dictionary in the results set, those keys then exist so when it tries to add the next one it errors because it cannot add an entry with those keys again.

I would suggest some sort of dynamic approach to key generation to that they are unique each time.
 
Share this answer
 

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