0

Please I need help to sort the following string in csv format alphabetically

Input
  First, Second,Third,Fourth, Fifth
  Beth,Charles,Danielle,Adam,Eric\n
  17945,10091,10088,3907,10132\n
  2,12,13,48,11



Output (After sorting)
  First, Second,Third,Fourth, Fifth
  Adam,Beth,Charles,Danielle,Eric\n
  3907,17945,10091,10088,10132\n
  48,2,12,13,11


This is what I have tried.

First I converted the csv into datatable

        var rows = csv.Split('\n', StringSplitOptions.RemoveEmptyEntries);
        var dtCsv = new DataTable();
        for (int i = 0; i < rows.Count(); i++)
        {
            string[] rowValues = rows[i].Split(','); //split each row with comma to get individual values  
            {

                if (i == 0)
                {
                    for (int j = 0; j < rowValues.Count(); j++)
                    {
                        dtCsv.Columns.Add(rowValues[j]); //add headers  
                    }
                }
                else
                {
                    //DataRow dr = dtCsv.NewRow();
                    for (int k = 0; k < rowValues.Count(); k++)
                    {
                        //dr[k] = rowValues[k].ToString();
                        dtCsv.Columns.Add(rowValues[k]);
                    }
                    // dtCsv.Rows.Add(dr); //add other rows  
                }
            }
        }

Then I tried to convert back to csv hoping i can be able to sort the datatable, but I am hooked.

I appreciate in advcance. Please I would appreciate a diferent approach if possible.

A.Tony
  • 1
  • 1
  • Is this homework? Do you have to use a DataTable? If you want to sort a DataTable you can use its DefaultView to apply a sort string. See this link to for help sorting a DataTable using the DefaultView as well as some LINQ examples, [sorting rows in data table](https://stackoverflow.com/questions/9107916/sorting-rows-in-a-data-table). – quaabaam Apr 15 '22 at 23:26
  • Your current `DataTable` has NO rows. The code simply adds columns to the table… ? … – JohnG Apr 15 '22 at 23:28
  • @quaabaam Thanks for the response, but I don't have to use a datatable, I just wanted another approach in solving the problem. – A.Tony Apr 15 '22 at 23:29
  • @JohnG Please suggest a different approach to solving the problem and getting the desired output – A.Tony Apr 15 '22 at 23:31
  • To @JohnG point, before you can sort the data you need to properly build your DataTable, which you are currently not doing. [how to create data table](https://stackoverflow.com/questions/1042618/how-to-create-a-datatable-in-c-sharp-and-how-to-add-rows) – quaabaam Apr 15 '22 at 23:32
  • Have you considered making a Class call it `Data` with three `string` properties? Then read the csv into a `List`… then you could sort it any way you want. – JohnG Apr 15 '22 at 23:33
  • 1
    Another option besides the data table would be using LINQ with objects. This is what @JohnG is getting at with his comment suggesting you use 'List'. – quaabaam Apr 15 '22 at 23:36
  • I considered creating a class and reading the csv into the class. However the columns should be dynamic. Could contain 1, 2, 3 or more columns – A.Tony Apr 15 '22 at 23:38
  • I do not see ANY column descriptions in the current data. After a closer look… the data looks odd. I would think a CSV file with headers may look something like… `Name,Num1,Num2\n” … then each row would be something like… “Beth,17945,2\n” … “Charles,10091,12\n” etc… Reading the data in its current state is going to require something a little more complex. Also, unless you are not allowed to use a third-party CSV I highly recommend you use one. – JohnG Apr 15 '22 at 23:48
  • @JohnG, I have update the question with the headers, please – A.Tony Apr 15 '22 at 23:51
  • I mean no disrespect, however... It appears you have this Row/Columns concept backwards. In your example you want to sort the COLUMNS…? … typically, you would sort by ROWS. But the way you have organized the data where each column is really a row… only complicates this sorting. Can you alter the data to be stored as I commented previously? I am just saying that storing data the way you have it is NOT normal and there are obvious reasons “why” the data is typically NOT stored as you have shown. – JohnG Apr 16 '22 at 00:25

1 Answers1

0

Although the model of data that you presented is not normal and accurate as Row, Column model, you can do it as per the below snippet code:

    static void Main(string[] args)
    {
        Dictionary<int, List<string>> myDummyDic = ReadDataFromCsv();

        foreach (var item in myDummyDic[0])
        {
            Console.WriteLine(item);
        }
    }

    private static Dictionary<int, List<string>> ReadDataFromCsv()
    {
        Dictionary<int, List<string>> myDummyDic = new();

        var result = File.ReadLines("data.csv")
            .Select(line => line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList());

        int rowC = 0;
        foreach (var item in result)
        {
            List<string> lst = new();
            for (int i = 0; i < item.Count; i++)
            {
                lst.Add(item[i]);
            }
            lst.Sort();
            myDummyDic.Add(rowC++, lst);
        }

        return myDummyDic;
    }

The output result:

Simple console result

Note that if you want to Transpose your CSV file entirely then I suggest you use Cinchoo ETL for that purpose.

Consider the following Question and Answers :

How to transpose matrix?

An approach without external library

Another approach using Cinchoo ETL to Transpose

Reza Heidari
  • 1,192
  • 2
  • 18
  • 23
  • Ok, thanks let me try this approach. I'd get back shortly – A.Tony Apr 16 '22 at 00:01
  • the output result isn't at expected. The names sorted quit alright, however that rest data remained same. for instance, in my question, the last row with number '48' belongs to the 'Adam' Column. So if we are to sort the string, that number should be in same position as Adam. – A.Tony Apr 16 '22 at 00:18
  • I see. That changes everything. You are looking to `Transpose`. And it is not possible to update the entire post, but I added some references for you. Check the updated post – Reza Heidari Apr 16 '22 at 09:26
  • Will do and revert shortly – A.Tony Apr 16 '22 at 09:59