5

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>

4 Answers 4

6
string result=list.Select(w=>w.Key+";"+w.Value).Aggregate((c,n)=>c+","+n);
Sign up to request clarification or add additional context in comments.

2 Comments

How would I modify this to handle an empty dictionary. Split out the select from the aggregate?
If it's empty, just don't do anything: string result=list.Count>0?list.Select(w=>w.Key+";"+w.Value).Aggregate((c,n)=>c+","+n):"";
3

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

Comments

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

I think (untested).

Comments

1

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.