0

I am new here and actually very new to c#. In a nutshell, I am using c# via Visual Studio, I am calling a data from a database and I want to save these data in a .csv file. The problem now is that I want to save these data on two columns at the same time.

My code do write them in a file but shifted not on the right rows.

        Dictionary<string, string> elementNames = new Dictionary<string, string>();
        Dictionary<string, string> elementTypes = new Dictionary<string, string>();
        var nodes = webservice.nepService.GetAllElementsOfElementType(webservice.ext, "Busbar", ref elementNames, ref elementTypes);
        Dictionary<string, string> nodeResults = new Dictionary<string, string>();
        Dictionary<string, string> nodeResults1 = new Dictionary<string, string>();
        foreach (var nodename in elementNames.Values)
        {
            var nodeRes = webservice.nepService.GetResultElementByName(webservice.ext, nodename, "Busbar", -1, "LoadFlow", null);
            var Uvolt = GetXMLAttribute(nodeRes, "U");                
            nodeResults.Add(nodename, Uvolt);                          
            var Upercentage = GetXMLAttribute(nodeRes, "Up");
            nodeResults1.Add(nodename, Upercentage);
    StringBuilder strBldr = new StringBuilder();
            string outputFile = @"C:\Users\12.csv";
            string separator = ",";   

            foreach (var res in nodeResults)
            {
                strBldr.AppendLine($"{res.Key}{separator}{res.Value}");
            }

            foreach (var res1 in nodeResults1)
            {

                strBldr.AppendLine($"{separator}{separator}{res1.Value}");
            }

            File.WriteAllText(outputFile, strBldr.ToString());
        }

this is the output of the previous code: https://ibb.co/T4trQC3

I want these shifted values to move up beside the other values like that: https://ibb.co/4S25v0h Thank you

  • 1
    Could you show a sample of what you'd expect the new output to be? Also, you should change the output in your post to reflect the actual output (you code has a comma as a delimiter, but you output is space-delimited). – Broots Waymb Apr 04 '19 at 16:02
  • I want the output to be distributed normally. It is actually has a separator in the csv file but here I cant show it correctly. Anyway, I want the output to be illustrated as normal file contains three columns one for the key (N1 and so on) and other two for values from res and res1. Thank you – Ahmed Abdel-Raouf Mohamed Apr 04 '19 at 16:05
  • This is the current output: https://ibb.co/T4trQC3 This is what I want: https://ibb.co/4S25v0h – Ahmed Abdel-Raouf Mohamed Apr 04 '19 at 16:15
  • https://stackoverflow.com/questions/18757097/writing-data-into-csv-file-in-c-sharp take a look in this thread – Ido H Levi Apr 04 '19 at 16:16
  • Instead of writing from inside the foreach, build you column and then push it at the same time – Ido H Levi Apr 04 '19 at 16:17

2 Answers2

0

if you look to the code you are using AppendLine

            strBldr.AppendLine($"{separator}{separator}{res1.Value}");

and if you want to append on same line just use Append

            strBldr.Append($"{separator}{separator}{res1.Value}");

EDITED:

in linq you can use Zip function to zip to lists

 // using System.Linq;
  var results = Results.Zip(Results1, (firstList, secondList) => firstList.Key + "," + firstList.Value + "," + secondList.Value);

Edit Full example

public static IDictionary<string, string> Results { get; set; }
    public static IDictionary<string, string> Results1 { get; set; }


    private static void Main(string[] args)
    {

    StringBuilder strBldr = new StringBuilder();
        string outputFile = @"D:\12.csv"; 
        Results = new Dictionary<string, string>()
        {
            {"N1", "20"},
            {"N2", "0.399992"},
            {"N3", "0.369442"},
            {"N4", "0.369976"}
        };
        Results1 = new Dictionary<string, string>()
        {
            {"N1", "100"},
            {"N2", "99.9805"},
            {"N3", "92.36053"},
            {"N4", "92.49407"}
        };
        IEnumerable<string> results = Results.Zip(Results1,
            (firstList, secondList) => firstList.Key + "," + firstList.Value + "," + secondList.Value);


        foreach (string res1 in results)
        {
            strBldr.AppendLine(res1);
        }


        File.WriteAllText(outputFile, strBldr.ToString());
    }

for faster code you can try this

HashSet<Tuple<string, string, string>> values = new HashSet<Tuple<string, string, string>>();

        var nodes = webservice.nepService.GetAllElementsOfElementType(webservice.ext, "Busbar", ref elementNames, ref elementTypes);

        foreach (var nodename in elementNames.Values)
        {
            var nodeRes = webservice.nepService.GetResultElementByName(webservice.ext, nodename, "Busbar", -1, "LoadFlow", null);
            var Uvolt = GetXMLAttribute(nodeRes, "U");
            var Upercentage = GetXMLAttribute(nodeRes, "Up");
            values.Add(Tuple.Create(nodename, Uvolt, Upercentage));
        } 

        var output = string.Join("\n", values.ToList().Select(tuple => $"{tuple.Item1},{tuple.Item2},{tuple.Item3}").ToList());
        string outputFile = @"C:\Users\12.csv";

        File.WriteAllText(outputFile, output); 
Khaled Sameer
  • 296
  • 2
  • 10
  • the problem is that I am calling data from two foreach loops. That's why when I tried strBldr.Append didn't work correctly with me. – Ahmed Abdel-Raouf Mohamed Apr 04 '19 at 16:09
  • your question is not so clear, can you provide more detail what is the Type of lists you are using `typeof(Results)` and `typeof(Results1)` – Khaled Sameer Apr 04 '19 at 16:21
  • Thank you Khaled for your help. It works with predefined values as you provided in the example. However, I call results from database after doing some analysis. I have added the full part of the code in the question for your information. Thank you – Ahmed Abdel-Raouf Mohamed Apr 04 '19 at 17:03
0

if the rowCount for Results and Results1 are same and the keys are in the same order, try:

for (int i = 0; i < Results.Count; i++) 
   strBldr.AppendLine($"{Results[i].Key}{separator}{Results[i].Value}{separator}{Results1[i].Value}");

Or, if the rows are not in the same order, try:

foreach (var res in Results)
   strBldr.AppendLine($"{res.Key}{separator}{res.Value}{separator}{Results1.Single(x => x.Key == res.Key).Value}");
Matt.G
  • 3,586
  • 2
  • 10
  • 23