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

.NET ProgrammingC#

Avatar of undefined
Last Comment
Fernando Soto

8/22/2022 - Mon
ste5an

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

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

What is your column terminator? When it's not the comma, then you don't need it. See also RFC 4180.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
nightshadz

ASKER
I don't know. I'm just building the CSV file and need to put quotes around each of the values.
ASKER CERTIFIED SOLUTION
Fernando Soto

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
nightshadz

ASKER
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 Soto

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.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.