patterncsharpMinor
Strongly-typed reading values from CSV DataTable
Viewed 0 times
readingdatatablecsvstronglytypedvaluesfrom
Problem
Is there a way to do this using parameters so the value is automatically converted to whatever datatype the keyfield has in the datatable?
This code should be reusable for future bulk update applications hence the constant and the check on multiple datatypes.
This code should be reusable for future bulk update applications hence the constant and the check on multiple datatypes.
private const string DBKEYFIELDNAME = "CustomerNr";
...
for (int i = 1; i skip header line
{
string[] csvFieldsArray = csvLines[i].Split(';');
int indexKeyField = csvHeaders.IndexOf(CSVKEYFIELDNAME.ToLower());
object csvKeyValue = csvFieldsArray[indexKeyField];
// ... some more code here that is not relevant
// Find the matching row for our csv keyfield value
Type keyType = parameters.DataTableOriginal.Columns[DBKEYFIELDNAME].DataType;
DataRow[] rowsOriginal = null;
if (keyType.IsAssignableFrom(typeof(string)))
rowsOriginal = parameters.DataTableOriginal.Select(DBKEYFIELDNAME + "='" + csvKeyValue.ToString() + "'");
else if (keyType.IsAssignableFrom(typeof(Int16)) || keyType.IsAssignableFrom(typeof(Int32)) || keyType.IsAssignableFrom(typeof(Int64)) || keyType.IsAssignableFrom(typeof(bool)))
rowsOriginal = parameters.DataTableOriginal.Select(DBKEYFIELDNAME + "=" + csvKeyValue);
if (rowsOriginal != null && rowsOriginal.Length == 1)
{
// Do some processing of the row here
}
}Solution
A few comments:
-
I would try to write the call to
- This method does way too much. It is difficult to understand and will be difficult to debug and maintain. Break it down into smaller methods that each have a single responsibility.
- Use curly braces after your if and else statements. This improves readability of the code and makes it less likely for other code to sneak in there in the future.
- Can't your else statement just be a plain else with no if after it? It seems like you want to put quotes around a string, and use the plain value for everything else. Are there other requirements here?
- The type of csvKeyValue could just be string, since it's pulling a value out of a string[]
- No need for the call to .ToString() in your if branch
-
I would try to write the call to
parameters.DataTableOriginal.Select only once. Consider using your if/else to set a delimeter variable to either string.Empty or ', then write your query once like so:DataRow[] rowsOriginal = parameters.DataTableOriginal.Select(
DBSLEUTELVELDNAAM + "=" + delimeter + csvKeyValue + delimeter);Code Snippets
DataRow[] rowsOriginal = parameters.DataTableOriginal.Select(
DBSLEUTELVELDNAAM + "=" + delimeter + csvKeyValue + delimeter);Context
StackExchange Code Review Q#800, answer score: 7
Revisions (0)
No revisions yet.