Search code examples
c#.netsortingcolumnsorting

Sort a variable based on header text


I am looking for guidence, and as I tried to convey with my title, I have an issue where I receive data that sometimes look like this for example :

entry[0] = "SHAPE", "X", "Y"
entry[1] = "Circle", "2", "3"

and sometimes may look like this:

entry[0] = "X", "Y", "SHAPE"
entry[1] = "2", "3", "Circle"

As you can see, they are ordered based on the first row values, which I will call "headerValues" below. I am now trying to map my variables (for example "shape") so it's placed where the entry actually correlates to the shape value. I want to do this so I dont end up with a X number in my "Shape" variable due to a different input order then I planned for.

I am also well aware that I may want to remove the first row before I add them into my shapes, but that is an issue I want to try and figure out on my own in order to learn. I am only here due to the fact that I have been stuck on this problem for a while now, and therefore really appriciate any help I can get from a more seasoned programmer than me.

Below you will find the code:

var csvRows = csvData.Split(';');
        var headerValues = csvRows[0].Split(',');

        List<Shapes> shapes = new List<Shapes>();
        if (csvRows.Count() > 0)
            foreach (var row in csvRows)
            {
                var csvColumn = row.Split(',').Select(csvData => csvData.Replace(" ", "")).Where(csvData => !string.IsNullOrEmpty(csvData)).Distinct().ToList();
                    if (csvColumn.Count() == 5)
                    {
                        shapes.Add(new()
                        {
                            shape = csvColumn[0], //want to have same index palcement as where headervalue contains = "Shape"


                        });
                    }
                    else
                    {
                    Console.WriteLine(row + " does not have 5 inputs and cannot be added!");
                    }
            }  

Thank you in advance!


Solution

  • You can determine your column(s) by using linq:

    var colShape = headerValues.ToList().FindIndex(e => e.Equals("SHAPE"));

    and then use that to set the the property in the object:

    shapes.Add(new()
    {
        shape = csvColumn[colShape], //want to have same index palcement as where headervalue contains = "Shape"
    
    });
    

    In the long run you would be better off using a csv parsing library.