Link to home
Start Free TrialLog in
Avatar of nightshadz
nightshadzFlag for United States of America

asked on

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

Avatar of ste5an
ste5an
Flag of Germany image

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.
Avatar of nightshadz

ASKER

v is a string. A value that would need quotes around it would look like this: "Durden2, Tyler2 F."
What is your column terminator? When it's not the comma, then you don't need it. See also RFC 4180.
I don't know. I'm just building the CSV file and need to put quotes around each of the values.
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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!!
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.