Regex To Linq to Dictionary in C#
This article demonstrates these concepts:
- Regex extraction of Key Value pairs and placing them into named capture groups.
- Linq extraction of the Key Value pairs extracted from the matches of Regex.
- Dictionary creation from Linq using the ToDictionary method.
I answered this on the MSDN forums, the user had this data in key value pairs delimited by the pipe:
abc:1|bbbb:2|xyz:45|p:120
Keys values separators
The need was to get the keys and values into a dictionary. The following code uses named regex group matches which are used in Linq to extract the keys and their values. Once that is done within the linq the extended method ToDictionary is used to create the dictionary on the fly. Here is the code:
string input = "abc:1|bbbb:2|xyz:45|p:120"; string pattern = @"(?<Key>[^:]+)(?:\:)(?<Value>[^|]+)(?:\|?)"; Dictionary<string, string> KVPs = ( from Match m in Regex.Matches( input, pattern ) select new { key = m.Groups["Key"].Value, value = m.Groups["Value"].Value } ).ToDictionary( p => p.key, p => p.value ); foreach ( KeyValuePair<string, string> kvp in KVPs ) Console.WriteLine( "{0,6} : {1,3}", kvp.Key, kvp.Value ); /* Outputs: abc : 1 bbbb : 2 xyz : 45 p : 120 */