I need a helper function to convert string like "1=alice;2=bob;3=charlie"
into a Dictionary<int, string>
, and string like "1=true;2=false;3=true"
into a Dictionary<int, bool>
, and etc.
To do this, I wrote a lot of helper functions that are basically copy and pasted of each other:
private static void load(Dictionary<int, string> dict, string s)
{
dict.Clear();
string[] items = s.Split(';');
foreach (string item in items)
{
if (item.Contains("="))
{
string[] kv = item.Split('=');
dict[int.Parse(kv[0])] = kv[1];
}
}
}
private static void load(Dictionary<int, bool> dict, string s)
{
dict.Clear();
string[] items = s.Split(';');
foreach (string item in items)
{
if (item.Contains("="))
{
string[] kv = item.Split('=');
dict[int.Parse(kv[0])] = bool.Parse(kv[1]);
}
}
}
private static void load(Dictionary<int, int> dict, string s)
{
dict.Clear();
string[] items = s.Split(';');
foreach (string item in items)
{
if (item.Contains("="))
{
string[] kv = item.Split('=');
dict[int.Parse(kv[0])] = int.Parse(kv[1]);
}
}
}
There are more, on other data types such as long
, DateTime
, and etc.
Is there a way to have just one helper function? I tried Dictionary<object, object>
and it didn't work.
Yes, you should have a generic method instead. Personally I'd make it return a new dictionary rather than clearing an existing one, mind you... and use LINQ to implement it:
private static Dictionary<int, T> Load<T>(string text, Func<string, T> parser)
{
return s.Split(';')
.Where(item => item.Contains("="))
.Select(item => item.Split('=', 2))
.ToDictionary(pair => int.Parse(pair[0]), pair => parser(pair[1]));
}
Then call it with:
Dictionary<int, int> foo = Load(text, int.Parse);
Dictionary<int, bool> bar = Load(text, bool.Parse);
Dictionary<int, string> baz = Load(text, x => x);
See more on this question at Stackoverflow