I have a string[] as below. Basically, this contains a set of filters and I want to separate them with a key. Key can be duplicate and if this happens then add comma separated value.
What is the best approach to that? Is any other alternative to Dictionary? If there is, then I am open for it.
Input:
var input = new List<string>
{
"Location=COL&StockNumber=1111150416",
"Location=NYC&StockNumber=2222250416&Invoice=Part",
"Location=NYC&StockNumber=2222250416&Invoice=Part&Supplier=AutoZone"
};
Expected Output:
var output = new Dictionary<string, string>
{
{ "Location", "(COL, NYC)" },
{ "StockNumber", "(1111150416, 2222250416, 2222250417)" },
{ "Invoice", "(Part)" },
{ "Supplier", "(AutoZone)" }
};
Issues
- If key already exists, then throws an error. Want to add bracket and comma separated value.
Code:
var testDictionary = new Dictionary<string, string>();
for(var i = 0; i < keys.Count; i++) {
var items = keys[i].Split("&");
for (var j = 0; j < items.Length; j++)
{
var data = items[j].Split("=");
if (testDictionary.ContainsKey(data[0]))
{
testDictionary[data[0]] = // ADD Comma separated value here but not sure how to do that.
}
testDictionary.Add(data[0], data[1]);
}
}
>Solution :
I suggest Linq query:
Given
var input = new List<string> {
"Location=COL&StockNumber=1111150416",
"Location=NYC&StockNumber=2222250416&Invoice=Part",
"Location=NYC&StockNumber=2222250416&Invoice=Part&Supplier=AutoZone"
};
We can get the required dictionary as (Fiddle)
using System.Linq;
...
var output = input
.SelectMany(line => line.Split('&'))
.Select(item => item.Split('='))
.GroupBy(pair => pair[0], pair => pair[1])
.ToDictionary(group => group.Key,
group => $"({string.Join(",", group.Distinct())})");
What’s going on:
- We split each string by
&and flatten the enumeration. Now we have enumeration of"Key=Value"strings - We split each
"Key=Value"by=into an arrayspair - We group by
pair[0](which will be Key)pair[1]s which will be values - We
JoinDistinctvalues for each Key - Finally, we materialize the result as
Dictionary