Search code examples
c#regexlinq

C#: Adding data to dictionary


I have a list like

List<string> TempList = new List<string> { "[66,X,X]", "[67,X,2]", "[x,x,x]" };

I need to add data to the dictionary from the above list

Dictionary<int, int> Dict = new Dictionary<int, int>();

so the Dict should contain

Key --> 66 value --> 67

i need to take 66(first value) from first string([66,X,X]) and 67(first value) from second string( [67,X,X]) and add it as a key value pair into the dictionary.

Now i'm following string replacing and looping methodology to do this .

Is there any way to do this in LINQ or Regular expression.


Solution

  • Here is an example using both string.Split() and a Regex:

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<string> data = new List<string>() { "[66,X,X]", "[67,X,2]", "[x,x,x]" };
                addToDict(data);
    
                Console.ReadKey();
            }
    
            private static void addToDict(List<string> items)
            {
                string key = items[0].Split('[', ',')[1];
                string val = items[1].Split('[', ',')[1];
    
                string pattern = @"(?:^\[)(\d+)";
                Match m = Regex.Match(items[0], pattern);
                key = m.Groups[1].Value;
                m = Regex.Match(items[1], pattern);
                val = m.Groups[1].Value;
    
                _dict.Add(key, val);
            }
    
            static Dictionary<string, string> _dict = new Dictionary<string, string>();
        }
    }
    

    i suspect that your example is quite contrived though, so there may be a better solution especially if you need to process large numbers of strings into key/value pairs (i deliberately hardcoded index values because your example was quite simple and i didn't want to over complicate the answer). If the input data is consistent in format then you can make assumptions like using fixed indexes, but if there is a possibility of some variance then there may need to be more code to check the validity of it.