简体   繁体   中英

Output data to CSV specific columns from Dictionary c#

I am trying to output the values from the dictionary to the CSV and am able to do this. But facing issue with the specific columns this need to output to the csv. I need the specific data value from dictionary to be output to a specific column in csv.

Dictionary<string, List<string>> file = new Dictionary<string, List<string>>();

for (var i = 0; i < stringList.Count(); i++)
{
    string line = stringList[i];
    string path = line.Replace("\r\n", "");
    path = path.Replace(" ", "");
    path = path.TrimEnd(':');

    if (File.Exists(path))
    {
        file[path] = file.ContainsKey(path) ? file[path] : new List<string>();
        for (var j = i + 1; j < stringList.Count(); j++)
        {
            string line2 = stringList[j];
            string path2 = line2.Replace("\r\n", "");
            path2 = path2.Replace(" ", "");
            path2 = path2.TrimEnd(':');

            if (File.Exists(path2))
            {
                i = j - 1;
                break;
            }
            else
            {
                if (path2.Contains("Verified") | path2.Contains("Algorithm"))
                {
                    var strings = path2.Split(':');
                    var listValue = strings[1].Trim();
                    file[path].Add(listValue);
                }
            }
        }
    }
}                

using (var writer = new StreamWriter(outputdir + "\\output_" + 
        DateTime.Now.ToString("yyyy_MM_dd_HHmmss") + ".csv"))
{
    writer.WriteLine("FilePath,Signature,HashValueSHA1, HashValueSHA2, HashValueMD5, Other");
    foreach (var keyvaluepair in file)
    {
        if (!keyvaluepair.Value.Contains("Unsigned"))
        {
            var values = String.Join(",", keyvaluepair.Value.Distinct().Select(x => x.ToString()).ToArray());
            writer.WriteLine("{0},{1}", keyvaluepair.Key, values);
        }
    }
}

Current Output looks like below:

当前的CSV输出以及上面的代码

Sample output I need as below:

CSV输出

The Dictionary key(string) would hold the file path and the values(List) would hold something like below:

Signed sha1RSA md5RSA md5RSA

Signed sha1RSA sha1RSA sha256RSA sha256RSA

Please suggest how can I get the one as required output.

I had a longer answer typed, but I see the problem.

On this line

var values = String.Join(",", keyvaluepair.Value.Distinct().Select(x => x.ToString()).ToArray());

take out Distinct . It looks like you have the correct number of items in each string, but if a list contains multiple blank entries Distinct is eliminating the duplicates. If a list contains two or three blank entries you need all of them. If you delete duplicate blanks your columns won't line up.

Also, when you use Distinct there's no guarantee that items will come back in any particular order. In this case the order is very important so that values end up in the right columns.

So in your example above, even though there's a blank in the third column of the first row, the value from the fourth column ends up in the third column and the blank goes to the end.


That will likely fix the immediate problem. I'd recommend not using a List<string> when you're expecting a certain number of values (they need to match up with columns) because a List<string> can contain any number of values.

Instead, try something like this:

public class WhateverThisIs
{
    public string Signature { get; set; }
    public string HashValueSha1 { get; set; }
    public string HashValueSha2 { get; set; }
    public string HashValueMd5 { get; set; }
    public string Other { get; set; }
}

Then, as a starting point, use Dictionary<string, WhateverThisIs> .

Then the part that outputs lines would look more like this:

var value = keyvaluepair.Value;
var values = String.Join(",", value.Signature, value.HashValueSha1, value.HashValueSha2,
    value.HashValueMd5, value.Other);

(and yes, that accounts for null values.)

If you want to replace nulls or empty values with "N/A" then you'd need a separate function for that, like

string ReplaceNullWithNa(string value)
{
    return string.IsNullOrEmpty(value) ? "N/A" : value;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM