O.O
O.O

Reputation: 11317

How to concatenate keys with values?

I am trying to create a string composed of a key followed by its value, such that the string looks something like:

key;value,key;value,key;value

So far I have tried to use concat:

var originalKeyValues = entity.ChangeTracker.OriginalValues.Keys.Concat(
    entity.ChangeTracker.OriginalValues.Values).ToString();

...but this doesn't seem to produce what I want.

Both Keys and Values are Dictionary<string, object>

Upvotes: 5

Views: 3959

Answers (4)

sandyiit
sandyiit

Reputation: 1705

Besides the ones mentioned above:

result = (from a in list select a.Key + ";" + a.Value).Aggregate((current, next) => current + "," + next);

we can also try the simple for loop without using linq :

foreach (KeyValuePair<String, String> a in list)
            result += a.Key + ";" + a.Value + ",";

Or we can use the .NET 4 feature of String.Join :

result = String.Join(",", (from a in list select a.Key + ";" + a.Value));

Upvotes: 1

BrunoLM
BrunoLM

Reputation: 100361

I would do like this:

var x = new Dictionary<string, string> { { "key", "value" }, { "key2", "value2" } };

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

From the dictionary select a enumerable of string then join the list by ,.

Output: key;value,key2;value2

Upvotes: 3

Blindy
Blindy

Reputation: 67447

string result=list.Select(w=>w.Key+";"+w.Value).Aggregate((c,n)=>c+","+n);

Upvotes: 6

George Duckett
George Duckett

Reputation: 32438

var originalKeyValues = entity.ChangeTracker.OriginalValues
    .Select(OV => OV.Key + ";" + OV.Value)
    .Aggregate((acc, next) => acc + "," + next));

I think (untested).

Upvotes: 1

Related Questions