none
Error msg on linq to dictionary-“an item of the same key value has already been added” RRS feed

  • Question

  • I'm trying do make a collection using linq based on ID which is a GUID.On using dictionary I'm getting error "An item with same key has already been added" Any suggestion?

    var resources = from r in datacontext.item_tables's
                                     select r.itemID; 
                                  
                     Collection collection = new Collection(); 
                    collection.Name = "Items"; 
      
                Guid[] ar= resources.ToArray<Guid>(); 
                foreach (Guid i in ar) 
                                  { 
     
     
                       var prod = (from r in datacontext.item_tables'
    s where r.itemID == i select r); 
               
    Dictionary<Guid, item_tables> tempdata =prod.ToDictionary(s => s.itemID); 
                
    Facet[] ftemp = new Facet[tempdata.Count]; 
                      
    string s1 = ""; 
                       
                       ftemp
    [0] = new Facet("descriptiob", FacetType.Text, tempdata[i].Description); 
     
                       ftemp
    [1] = new Facet("date", FacetType.Text, tempdata[i].uploaddate); 
     
                       
                      
    for (int iv = 0; iv < tempdata.Count; iv++) 
                      
    { 
     
                           
                           s1
    += tempdata[i].ProductName + " \n";  
                      
    } 
     
                       ftemp
    [2] = new Facet("ProductName", FacetType.Text, s1); 
     
                       collection
    .AddItem(tempdata[i].ItemName, null, null, 
                                
                                     ftemp
    [0], ftemp[1], ftemp[2] 
                                    
    ); 
                  
    }

    Monday, May 21, 2012 1:34 AM

Answers

  • First off, using the code insertion tool makes the code render correctly in the post, that helps a lot.

    Secondly a dictionary doesn't allow duplicate keys, your code is actually picking all elements that coincide with a specific guid in a datacontext and using that as a key to insert all the elements which of course prompt that error.

    Regards

    Monday, May 21, 2012 6:27 PM