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

nightshadz
nightshadz used Ask the Experts™
on
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

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
ste5anSenior Developer

Commented:
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.

Author

Commented:
v is a string. A value that would need quotes around it would look like this: "Durden2, Tyler2 F."
ste5anSenior Developer

Commented:
What is your column terminator? When it's not the comma, then you don't need it. See also RFC 4180.
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

Author

Commented:
I don't know. I'm just building the CSV file and need to put quotes around each of the values.
Retired
Distinguished Expert 2017
Commented:
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

Author

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!!
Fernando SotoRetired
Distinguished Expert 2017

Commented:
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.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial