Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

need help in adding objects in dictionary, so when there is new object i am adding key & object but struggling with object because i cant cast it or am doing something wrong ? & it already has the key am appending value to list on same key
C#
Dictionary<string, list<object="">> uniqueComp = new Dictionary<string, list<object="">>();

if(!uniqueComp.ContainsKey( cmp1[i].name))
  {
      
      uniqueComp.Add(cmp1[i].name,(System.Collections.Generic.List) cmp1[i]);
  }
  if (uniqueComp.ContainsKey(cmp1[i].name))
  {
// append new object in exisitng key
  }


Please help

What I have tried:

List<object>>();

if(!uniqueComp.ContainsKey( cmp1[i].name))
  {
      
      uniqueComp.Add(cmp1[i].name,(System.Collections.Generic.List) cmp1[i]);
  }
  if (uniqueComp.ContainsKey(cmp1[i].name))
  {
// append new object in exisitng key
  }
Posted
Updated 13-Apr-24 7:49am
v2

Your code should look something like this:
C#
if (!uniqueComp.ContainsKey(cmp1[i].name))
{
  uniqueComp.Add(cmp[i].name, new List<object>());
}
uniqueComp[cmp[i].name].Add(... whatever the value is ...);
Basically, you are testing to see whether you have the key or not and, if not, you add a list. At this point, you know that you have the list present, so you can simply call the Add method. You don't need to test whether the key is present again.
 
Share this answer
 
Comments
Richard Deeming 12-Apr-24 7:51am    
You can use TryGetValue to reduce the key lookups:
if (!uniqueComp.TryGetValue(cmp1[i].name, out List<object> list))
{
    list = new List<object>();
    uniqueComp.Add(cmp1[i].name, list);
}

list.Add(...);
Pete O'Hanlon 12-Apr-24 8:26am    
This is true and it's such a great reply, you should add it to the question so I can award it as many points as possible and recommend it as the accepted answer.
Further to Pete's excellent answer, you can use the TryGetValue method[^] to avoid the double key lookup of ContainsKey followed by the indexer:
C#
if (!uniqueComp.TryGetValue(cmp1[i].name, out List<object> list))
{
    list = new List<object>();
    uniqueComp.Add(cmp1[i].name, list);
}

list.Add(...);
You could even turn this pattern into an extension method, inspired by the ConcurrentDictionary<TKey, TValue>'s GetOrAdd method[^]:
C#
public static class DictionaryExtensions
{
    public static TValue GetOrAdd<TKey, TValue>(
        this IDictionary<TKey, TValue> dictionary,
        TKey key,
        Func<TKey, TValue> valueFactory)
    {
        if (!dictionary.TryGetValue(key, out TValue value))
        {
            value = valueFactory(key);
            dictionary.Add(key, value);
        }
        
        return value;
    }
}
which would then make your code:
C#
List<object> list = uniqueComp.GetOrAdd(cmp1[i].name, _ => new List<object>());
list.Add(...);
 
Share this answer
 
Comments
Pete O'Hanlon 12-Apr-24 9:32am    
I know it's only a measly 5 from me, but I wish I could award this 50 on style points alone. Very elegant.
Pete O'Hanlon 12-Apr-24 9:33am    
If an answer is going to be marked as the accepted answer, it should be this one.
Member 14224038 12-Apr-24 10:13am    
thanks for the answers guys but i think it wont work when i have multiple objects of same type

So my primary array is like below

(cmp1.name, nut)
(cmp2.name, bolt)
(cmp1.name, nut)
(cmp3.name, washer)
(cmp1.name, nut)
(cmp1.name,nut)
(cmp3.name, washer)

I can have the key & I can have mulitple values in arraylist again & when i say below
if (!uniqueComp.TryGetValue(cmp1[i].name, out List<object> list))
{
list = new List<object>();
uniqueComp.Add(cmp1[i].name, list);
}
there will be new list & delete already old entry for cmp1.name (key) ?
SO i am looking to group nut, bolt, washer in above case.
So the output would be like
(key(cmp1.name, list of(nut)x4))
(key(cmp2.name, list of(bolt)x1))
(key(cmp3.name,list of(washer)x2))
Richard Deeming 12-Apr-24 10:15am    
No. If the dictionary already contains the specified key, then TryGetValue will return true, and the list variable will contain the existing value for that key.

The only time it creates a new list is if TryGetValue returns false, meaning that the key does not already exist in the dictionary.
George Swan 12-Apr-24 17:51pm    
Is the extension method example correct? Will it accept a new List as a Func that takes a key and returns a value?

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