Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join keys and values from Dictionary

Tags:

c#

dictionary

Is there a way to quickly (i.e. without using foreach) concat the following Dictionary:

Dictionary<string, string> g = new Dictionary<string, string>();
g.Add("K", "k1");
g.Add("L", "l1");

into

"K=@K,L=@L"

and what about getting this result: "K=k1,L=l1" ?

I am playing a little with String.Join, but that doesn't seem to do what I want.

Some background: I have a list of key/value pairs I want to either INSERT in my database (...keys...) VALUES (...values...) or UPDATE a records ...,key=value, ....

like image 633
Bart Friederichs Avatar asked Dec 17 '15 20:12

Bart Friederichs


2 Answers

You can do this fairly easily with LINQ, it still is using foreach under the covers so it won't be any "faster" but it should be easy to read.

Dictionary<string, string> g = new Dictionary<string, string>();
g.Add("K", "k1");
g.Add("L", "l1");

var keys1 = g.Select(x=>String.Format("{0}=@{0}", x.Key));
var result1 = String.Join(",", keys1);
Console.WriteLine(result1);

var keys2 = g.Select(x=>String.Format("{0}={1}", x.Key, x.Value));
var result2 = String.Join(",", keys2);
Console.WriteLine(result2);

Run Code

The first thing we do is we make a IEnumerable<String> of the items we want, we then use string.Join to combine that IEnumerable in to a single string.

EDIT:
If you are updating in to a database I recommend dropping this approach and try out some ORM libraries like Entity Framework or NHibernate. They do all this work for you and make it much easier to work with objects and not worry about generating dynamic queries.

like image 124
Scott Chamberlain Avatar answered Oct 05 '22 10:10

Scott Chamberlain


The shortest code I can think of is

string res = string.Join("\n", g.Select(p => "K=" + p.Key + ",L=" + p.Value));

This results in

K=K,L=k1
K=L,L=l1
like image 39
helb Avatar answered Oct 05 '22 10:10

helb