'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 1:[1]

Since your data is in the CSV format, you don't need to reinvent the wheel, just use a helper library like CsvHelper

using var reader = new StringReader(csvData);
using var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture);
var shapes = csvReader.GetRecords<Shapes>().ToList();

You may need to annotate the Shapes.shape field or property if it has different casing from the data, use the NameAttribute provided by CsvHelper

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sarmad Georgie