0

I'm looking for some guidance on how to split a string into object properties in C#, I'm struggling with how to do it.

For example I have a string of a filename like

Artist, Song, CreationDateTime

And I want to parse that into an object with properties of Artist, Song and CreationDateTime.

What would be the most efficient method? I'm struggling past delimiting the string by a comma into an array. From there it then can't be assigned to the properties.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sam strider
  • 13
  • 1
  • 3
  • 1
    You need to show us your actual data, not just say what you think it's “like”. If it's comma-separated consult questions on [CSV parsers](https://stackoverflow.com/questions/2081418/). – Dour High Arch Oct 21 '18 at 18:57
  • Depending on where that data comes from there are plenty of different ways to achueve this, e.g. some JSON-serializer, XML-serializer, CSV-reader... – MakePeaceGreatAgain Oct 21 '18 at 19:19

1 Answers1

2

This should help you:

            string strToParse = "MyArtist, MySong, MyCreationDate"; // your string
        string [] arrayOfStrings = strToParse.Split(',');       // split string to array by comma character
        if (arrayOfStrings.Length != 3) // check if you splitted correct, and have 3 entries
            return;

        var anonymousType = new { Artist = arrayOfStrings[0], Song = arrayOfStrings[1], Date = arrayOfStrings[2] }; // replace anonymous type with your type
PSMNH
  • 95
  • 6