1

I need to split a string into multiple substrings and store those substrings into a list.

Here is an example of the possible contents stored in my initial string:

  "{"Stocks": [{"APPLE-775121": false, "AMZN-007612": true, "GOLD-847571": true}]}"

The initial string is ever changing, their could be multiple stocks names in there. I need to extract these items only and store into a list of strings:

    APPLE-775121
    AMZN-007612
    GOLD-847571

Having a little trouble parsing the string, I'm new to C# and don't know about all the useful string functions that exist.

So far what I have done is parsed the InitialString to a new string (named ParsedString) which contains:

  "APPLE-775121": false, "AMZN-007612": true, "GOLD-847571": true

Can I get some help parsing the rest of this string and storing the substrings into a list? Thanks in advance!

ana steele
  • 45
  • 5

2 Answers2

3

You will first want to create a class to house that Stock data. From there, you can use Newtonsoft's Json conversion utilities and LINQ to extract your list. I forget which, but some project templates actually come with the Newtonsoft package already installed, but if it's not there by default, you can get it here.

void Main()
{
    var str = "{\"Stocks\": [{\"APPLE-775121\": false, \"AMZN-007612\": true, \"GOLD-847571\": true}]}";
    var obj = JsonConvert.DeserializeObject<StockContainer>(str);
    var stockList = obj.Stocks.SelectMany(dictEntry => dictEntry.Keys).ToList();
    Console.Write(stockList);  //this is what you want
}

public class StockContainer
{
    public List<Dictionary<string, bool>> Stocks {get;set;}
}
Steve Danner
  • 21,818
  • 7
  • 41
  • 51
  • The issue is I'm getting the initial string from a database, so I don't have control over initializing the string. I can't add those backslashes you added. Will it still work without adding those? – ana steele Jul 27 '20 at 20:01
  • 1
    @anasteele It will work, backlashes are here only to escape special characters :) – Michał Turczyn Jul 27 '20 at 20:02
  • 1
    @MichałTurczyn is correct. Assuming this is coming from a database, the .NET CLR will take care of it all for you. I added them in since I'm "hard-coding" the string for demonstration's sake. – Steve Danner Jul 27 '20 at 20:05
0

If you are sure, that list always be wrapped in [ and ], and items' names won't contain any [, ], {, } and , you can use simple string.Split:

var str = "{\"Stocks\": [{\"APPLE-775121\": false, \"AMZN-007612\": true, \"GOLD-847571\": true}]}";
var listOfItems = str.Split(new char[] { '[', ']', '}', '{' }, StringSplitOptions.RemoveEmptyEntries)[1];
var extractedItems = listOfItems.Split(',').Select(item => item.Split(':')[0]).ToArray();
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69