Search code examples
c#stringsubstringchars

Extract multiple substrings before / after certain chars


I'm looking to get multiple certain substrings before and after certain chars...e.g.:

"Capacity : Less than 10 litres |Power : Up to 1400 W|Type of surface : Carpets and rugs"

I need to get these in 2 lists of strings (or datatable or something like it for inserting into DB) getting all strings before and after the ':' char.. For example, 1st list from above would look like: 'Capacity, Power, Type of Surface' and their corresponding values: 'Less than 10 litres, Up to 1400 W, Carpets and rugs'

Any help would be greatly appreciated, thanks. (in C# if possible!)


Solution

  • You may wanna use a Dictionary instead of a list:

    var str = "Capacity : Less than 10 litres |Power : Up to 1400 W|Type of surface : Carpets and rugs";
    
    var values = str
                .Split('|')
                .ToDictionary(
                      x => x.Split(':')[0],
                      x => x.Split(':')[1]);