Convert String list to a dictionary - c#

I Have a string list like this ["saman=1", "kaman=2"]
How may I convert this to a dictionary like {Saman:1 , kaman:2}
strList.Select(k,v =>new {k,v} , k=> k.split('=')[0], val => v.split('=')[1]);

This should work:
strList.ToDictionary(x => x.Split('=')[0], x => x.Split('=')[1])
If you want Dictionary<string, int> you can parse the Value to integer:
strList.ToDictionary(x => x.Split('=')[0], x => int.Parse(x.Split('=')[1]))

You should split by ", " first, and then split each item by = to get key/value pairs.
Additional Trim call will get rid of [" at the beginning and "] at the end of your input string.
var input = #"[""saman=1"", ""kaman=2""]";
var dict = input.Trim('[', '"', ']')
.Split(new [] {#""", """}, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split('='))
.ToDictionary(x => x[0], x => x[1]);

Very, very simply with LINQ:
IDictionary<string, string> dictionary =
list.ToDictionary(pair => pair.Key, pair => pair.Value);
Note that this will fail if there are any duplicate keys - I assume that's okay?

Related

How to combine duplicate values in dictionary into one value

I have dictionary with duplicate values. How to join this duplicate values into one value
Example:
Accord - first
Accord.s - first
I want to see something like:
Accord, Accord.s - first
If I've understood you right, you have a dictionary
Dictionary<string, string> source = new Dictionary<string, string>() {
{"Accord", "first"},
{"Accord.s", "first"},
{"Gamma", "second"},
};
and you want to group by Value, which you can do with a help of Linq:
using System.Linq;
...
// If you want to create a dictionary:
Dictionary<string, string> result = source
.GroupBy(pair => pair.Value)
.ToDictionary(
chunk => string.Join(", ", chunk.Select(pair => pair.Key)),
chunk => chunk.Key);
string report = string.Join(Environment.NewLine, result
.Select(pair => $"{pair.Key} : {pair.Value}"));
Console.Write(report);
Outcome:
Accord, Accord.s : first
Gamma : second
In case you want just a query (not dictionary)
var result = source
.GroupBy(pair => pair.Value)
.Select(chunk => new {
Key = string.Join(", ", chunk.Select(pair => pair.Key)),
Value = chunk.Key});
// and then
string report = string.Join(Environment.NewLine, result
.Select(pair => $"{pair.Key} : {pair.Value}"));

Array of concatenated strings into Dictionary<int, int>

I have an array of strings. Each string is two numbers separated with a "|".
How can I get this array of string into Dictionary<int,int> without looping through the array, splitting each string and adding to the dictionary.
Is there a better way?
simply,
var result = strings
.Select(s => s.Split('|'))
.ToDictionary(a => int.Parse(a[0]), a => int.Parse(a[1]));
if duplicates are allowed,
var result = strings
.Select(s => s.Split('|'))
.ToLookup(a => int.Parse(a[0]), a => int.Parse(a[1]));
You can use ToDictionary method:
var dictionary = stringArray.ToDictionary(x => x.Split('|')[0], x => x.Split('|')[1]);
But you should be aware that this will throw an exception if there are duplicate keys.

Using Dictionary to count the number of appearances

My problem is that I am trying to take a body of text from a text box for example
"Spent the day with "insert famous name" '#excited #happy #happy"
then I want to count how many times each hashtag appears in the body, which can be any length of text.
so the above would return this
excited = 1
happy = 2
I Was planning on using a dictionary but I am not sure how I would implement the search for the hashtags and add to the dictionary.
This is all I have so far
string body = txtBody.Text;
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach(char c in body)
{
}
thanks for any help
This can be achieved with a couple of LINQ methods:
var text = "Spent the day with <insert famous name> #excited #happy #happy";
var hashtags = text.Split(new[] { ' ' })
.Where(word => word.StartsWith("#"))
.GroupBy(hashtag => hashtag)
.ToDictionary(group => group.Key, group => group.Count());
Console.WriteLine(string.Join("; ", hashtags.Select(kvp => kvp.Key + ": " + kvp.Value)));
This will print
#excited: 1; #happy: 2
This will find any hashtags in a string of the form a hash followed by one or more non-whitespace characters and create a dictionary of them versus their count.
You did mean Dictionary<string, int> really, didn't you?
var input = "Spent the day with \"insert famous name\" '#excited #happy #happy";
Dictionary<string, int> dic =
Regex
.Matches(input, #"(?<=\#)\S+")
.Cast<Match>()
.Select(m => m.Value)
.GroupBy(s => s)
.ToDictionary(g => g.Key, g => g.Count());

Convert string to Dictionary<string,byte>()

I have a string that is formatted like this (the string is one continuous, no new line return)
/CallDump/CallInfo/KVP[#Key='Group' and (#Value='Best Group')]:10,
/CallDump/CallInfo/child::KVP[#Key='Dept' and (#Value='Customer Service' or #Value='Sales')]:240,
compare(Recordings/Recording/Location, 'New York')=0:20,
default:5,
I cannot seem to find a non complex way to convert it into a dictionary()
results would be something like this:
Key: /CallDump/CallInfo/KVP[#Key='Group' and (#Value='Best Group')] Value: 10
Key: compare(Recordings/Recording/Location, 'New York')=0 Value: 20
You can easily do this with Regex and LINQ:
var input = #"/CallDump/CallInfo/KVP[#Key='Group' and (#Value='Best Group')]:10,
/CallDump/CallInfo/child::KVP[#Key='Dept' and (#Value='Customer Service' or #Value='Sales')]:240,
compare(Recordings/Recording/Location, 'New York')=0:20,
default:5,";
var expression = new Regex(#"(.+):(\d{1,3})");
var result = input.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim())
.Select(x => expression.Match(x))
.Select(m => new { Key = m.Groups[1].Value, Value = byte.Parse(m.Groups[2].Value) })
.ToDictionary(x => x.Key, x => x.Value);
Returns Dictionary<string, byte> with four elements.

C# split, return key/value pairs in an array

I'm new to C#, and thus am looking for layman's terms regarding this. Essentially, what I would like to do is turn:
key1=val1|key2=val2|...|keyN=valN
into a database array where, you guessed it, key1 returns val1, key2 returns val2, etc. I know I could return a string using split, but from that point on, I'm at a loss. Any help would be greatly appreciated! I hope I've made my intentions clear, but if you have any questions, don't hesitate to ask!
string s = "key1=val1|key2=val2|keyN=valN";
var dict = s.Split('|')
.Select(x => x.Split('='))
.ToDictionary(x => x[0], x => x[1]);
Now dict is a Dictionary<string, string> with the desired key/value pairs.
Dictionary<string,string> results = new Dictionary<string,string>();
foreach(string kvp in source.split('|'))
{
results.Add(kvp.split('=')[0], kvp.split('=')[1]);
}
Probably a Linq way of doing it.
string s = "key1=val1|key2=val2|keyN=valN";
var dict = s.Split('|')
.Select(x => x.Split('='))
.Where(x => x.Length > 1 && !String.IsNullOrEmpty(x[0].Trim())
&& !String.IsNullOrEmpty(x[1].Trim()))
.ToDictionary(x => x[0].Trim(), x => x[1].Trim());

Categories

Resources