, , XML. , .
- , . , . - :
Dictionary<string, string> map = new Dictionary<string, string>
{
{ "matchtype", null },
{ "matches", null },
{ "ballsbowled", null }
};
foreach (XmlElement elm in stats.SelectNodes("*"))
{
if (map.ContainsKey(elm.Name))
{
map[elm.Name] = elm.InnerText;
}
}
, , , . null, , ( ).
, DataTable, DataTable XML, , DataTable.Columns - . , DataColumn , , :
foreach (XmlElement elm in stats.SelectNodes("*"))
{
if (myTable.Columns.Contains(elm.Name))
{
DataColumn c = myTable.Columns[elm.Name];
if (c.DataType == typeof(string))
{
myRow[elm.Name] = elm.InnerText;
continue;
}
if (c.DataType == typeof(double))
{
myRow[elm.Name] = Convert.ToDouble(elm.InnerText);
continue;
}
throw new InvalidOperationException("I didn't implement conversion logic for " + c.DataType.ToString() + ".");
}
}
, - , , , , , .
Edit
, -, . Python; # , , - .
, , , DataColumn, , . , , :
Dictionary<string, Type> typeMap = new Dictionary<string, Type>
{
{ "matchtype", typeof(string) },
{ "matches", typeof(int) },
{ "ballsbowled", typeof(int) }
}
, :
if (typeMap[elm.Name] == typeof(int))
{
result[elm.Name] = Convert.ToInt32(elm.Text);
continue;
}
Dictionary<string, string>, , ; Dictionary<string, object>.
; , continue, - , . ? , :
Dictionary<Type, Func<string, object>> conversionMap =
new Dictionary<Type, Func<string, object>>
{
{ typeof(string), (x => x) },
{ typeof(int), (x => Convert.ToInt32(x)) },
{ typeof(double), (x => Convert.ToDouble(x)) },
{ typeof(DateTime), (x => Convert.ToDateTime(x) }
};
, -. Func<string, object> , string . , : -, . (x), . ( , x - ? Func<string, object> .)
, :
result[elm.Name] = conversionMap[typeMap[elm.Name]](elm.Text);
: typeMap, conversionMap , elm.Text .
. . , . Code Complete, , . . , . .