C# LINQ - Extract Values of Dictionary<string,string> as CSV

I'm trying to output the values of the Fields dictionary (Dictionary<string,string>) as a CSV file. I need to put quotes around each value but when I use...

var values = string.Join(",", "\"" + a.Fields.Select(v => v.Value) + "\"");

...it outputs as

"System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Collections.Generic.KeyValuePair`2[System.String,System.String],System.String]"

However, when I remove the quotations and use...

var values = string.Join(",", a.Fields.Select(v => v.Value));

...it outputs fine, but I need quotes around the values because some of the values contain commas.

        public void Print()
        {
            var csv = new StringBuilder();            
            var header = String.Join(",", audit[0].Fields.Select(k => k.Key));
            csv.Append(header);

            foreach (var a in audit)
            {
                var values = string.Join(",", "\"" + a.Fields.Select(v => v.Value) + "\"");
                csv.Append(Environment.NewLine + values);
            }

            File.WriteAllText(AppConfig.CSVFilePath(), csv.ToString());
        }

Open in new window

nightshadzAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ste5anSenior DeveloperCommented:
What type is v? Does a v.Value.ToString() work?

btw, you only need to enclose values in a CSV, when it contains a quotation mark or the column terminator.
0
nightshadzAuthor Commented:
v is a string. A value that would need quotes around it would look like this: "Durden2, Tyler2 F."
0
ste5anSenior DeveloperCommented:
What is your column terminator? When it's not the comma, then you don't need it. See also RFC 4180.
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

nightshadzAuthor Commented:
I don't know. I'm just building the CSV file and need to put quotes around each of the values.
0
Fernando SotoRetiredCommented:
Hi nightshadz;

I believe the issue you are having is that a.Fields.Select(v => v.Value) is returning a collection of strings and it does not know how to concatenate the character " to the collection. Try using the following line to replace yours, it should give the results you are looking for.

var values = a.Fields.Aggregate("", (aggregateFields, nextField)  => aggregateFields + "\"" + nextField.Value + "\",").TrimEnd(',');

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
nightshadzAuthor Commented:
As always Fernando, you are my hero.

I'll spend some time dissecting your code, and like all of your previous code suggestions, I will learn a lot in the process. Thanks again!!
0
Fernando SotoRetiredCommented:
Hi nightshadz;

The Aggregate method makes it simple to perform a calculation / manipulation over a sequence of values. This method works by calling function in the lambda expression one time for each element in the source sequence. Each time the function is called, the Aggregate method supply both the element from the sequence and an aggregated value (as the first argument to function). The first element of the source is used as the initial aggregate value. The result of function replaces the previous aggregated value. The Aggregate method returns the final result of the function.

From the above inside of the Aggregate method we have the empty string, "", this is here for two reasons, first to tell the method of the return type is a string and not a KeyValuePaire and secondly as the initial value for the aggregateFields. Next we look at lambda expression, (aggregateFields, nextField), where aggregateFields is the accumulated values of all the iterations and passed to the function with each iteration and the nextField is the next object from the Dictionary, KeyValuePaire also passed to the function. Now you have the function itself which is applied to each element of the Dictionary. Because we are concatenating strings as follows. The accumulated string concatinated with a " concatenated to the Value part of the KeyValuePair concatenated to the final " and a comma. When the Aggregate method is done the last method TrimEnd removes the final comma.

var values = a.Fields.Aggregate("", (aggregateFields, nextField)  => aggregateFields + "\"" + nextField.Value + "\",").TrimEnd(',');

Open in new window


Hope that helps.
1
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.