Home > Enterprise >  c# combine dictionary values into new key value pair
c# combine dictionary values into new key value pair

Time:11-03

I have a c# dictionary like this:

enter image description here

what I need to do is combine the values where Dictionary keys contains "UPC" into a new key with combined values so it reads like this: {[UPC, 000000000333, 789787878999]}

The UPCs could contain one or more values.

I came up with the code below to remove possible duplicates from a information dictionary first

enter image description here

//Remove any duplicates
        List<string> vals = new List<string>();
        Dictionary<string, string> newDict = new Dictionary<string, string>();
        foreach (KeyValuePair<string, string> item in information)
        {
            if (!vals.Contains(item.Value))
            {
                newDict.Add(item.Key, item.Value);
                vals.Add(item.Value);
            }
        }

        StringBuilder sbUPC = new StringBuilder();
        
        var newDictJustUPCs = newDict.Where(kvp => kvp.Key.Contains("UPC"));

The newDictJustUPCs returns the following:

enter image description here

So how would I loop thru these KeyValuePairs and create the KeyValue pair for newDict having the key "UPC" and the two values combined and assign it to newDict?

I know part of the final answer will be newDict.Add("UPC", CombinedUPCValues);

CodePudding user response:

First Extract out all UPC elements and create its value as you want and then append it to new array that dont have UPC elements

            var dict = new Dictionary<string, string>
        {
            {"Modified by", "Stuart gill" },
            {"Modified on", "11/2/2021" },
            {"UPC0", "000000000333" },
            {"UPC2", "789789789" },
        };

       var keyValueWithUpc = dict.Where(kv => kv.Key.StartsWith("UPC")).ToArray();
       var upcValue = string.Join(",", keyValueWithUpc.Select(kv => kv.Value));
       var result = dict.Except(keyValueWithUpc)
                         .Append(new KeyValuePair<string, string>("UPC", upcValue))
                         .ToDictionary(x => x.Key, x => x.Value);

Append method: It takes source (collection to append) an array instead of one , just to distinguish from existing one , but since it takes as an params you can also pass single item

public static class ExtensionMethods
{
    public static IEnumerable<T> Append<T>(this IEnumerable<T> source, params T[] itemsToAppend)
    {
        return source.Concat(itemsToAppend);
    }
}

CodePudding user response:

There are simply oodles of ways you can do this. Here is just one

Given

var dict = new Dictionary<string, string>
{
   { "asd", "dfgdfg" },
   { "ghj", "ghj" },
   { "UPC1", "123" },
   { "UPC2", "345" },
   { "UPC3", "567" }
};

Usage

var upc = dict
   .Where(x => x.Key.StartsWith("UPC"))
   .Select(x => x.Value);

var newDict = dict
   .Where(x => !x.Key.StartsWith("UPC"))
   .ToDictionary(x => x.Key, x => x.Value);

newDict.Add("UPC", string.Join(",", upc));


foreach (var item in newDict)
    Console.WriteLine(item.Key   " : "  item.Value);

Output

asd : dfgdfg
ghj : ghj
UPC : 123,345,567
  • Related