JadedEric
JadedEric

Reputation: 2083

Add value to generic dictionary by key

I have a generic dictionary I instantiate with a key, but a null value, because I need to build the value, out of an iteration, that can only be added to a unique key afterwards.

My question, is there an elegant way to add the instantiated collection to the dictionary by it's key?

My situation:

Values get stored in a collection of records' description block

[1]|[Category reference]
[2]|[Category reference]
[3]|[Category reference]
[1]|[Category reference 1]
[2]|[Category reference 2]

From this, I do a split on the the pipe {|} item, and then pull the category value and add that to an entity object, for each iteration out of this:

// I have a dictionary object to be used for categorization
Dictionary<string, List<FieldItem>> dict = 
                                    new Dictionary<string, List<FieldItem>>();

// need to store each field item in a List<T>
List<FieldItem> items = new List<FieldItem>();

// then I iterate each record from my data source, 
// and get the category from description
foreach (var item in records)
{
    string category = item.Description
                          .Split(new char[] { '|' })[1]
                          .Trim(new char[] { '[', ']');

    // this will give me the category for each item
    FieldItem fi = new FieldItem { Category = category }; // more items will be added

    if (!dict.Keys.Contains(category))
       dict.Add(category, null);

    items.Add(fi);   
}

// now, I have the List<FieldItem> collection and 
// each one contains a category, I now need to add this List<FieldItem>
// collection to Dictionary<string, List<FieldItem>> based on the
// category, so I tried this:

foreach (var kvp in dict.Keys)
{
    var addItem = items.Where(x => x.Category.Equals(kvp)).ToList(); // gives me collection

    // would it be elegant to delete the key from the collection first?
    // cannot do a delete here as the Dictionary is in use, so
    // thought of adding my items to a new Dictionary??

    dict.Add(kvp, addItem);
}

Upvotes: 0

Views: 127

Answers (1)

Ahmed KRAIEM
Ahmed KRAIEM

Reputation: 10427

foreach (var item in records)
{
    string category = item.Description
                          .Split(new char[] { '|' })[1]
                          .Trim(new char[] { '[', ']');

    // this will give me the category for each item
    FieldItem fi = new FieldItem { Category = category }; // more items will be added

    if (!dict.Keys.Contains(category))
       dict.Add(category, new List<FieldItem>());

    dict[category].Add(fi);   
}

Upvotes: 2

Related Questions