简体   繁体   English

C#中类型转换为SQL数据

[英]Type conversion in C# for SQL data

I have a DataTable which is filled from a SQL database.我有一个从DataTable数据库填充的数据表。 Values are returned as object type (also the Calculate function returns object as well for some reason), so I need to convert them to proper type.值返回为 object 类型( Calculate function 也出于某种原因返回 object),因此我需要将它们转换为正确的类型。 It makes the code so complicated.它使代码变得如此复杂。

Like this:像这样:

 double value;

 foreach (DataRow row in sampleDataTable.Rows)
 {
     value +=  (double)Global.Calculate(Convert.ToDouble(Global.dbNullCheck(row["value1"], 0)) / Convert.ToDouble(row["value2"]), 2);
 }

I can write above code as:我可以将上面的代码写成:

 double sum;
 double value1;
 double value2;

 foreach (DataRow row in sampleDataTable.Rows)
 {
     value1 = Convert.ToDouble(Global.dbNullCheck(row["value1"], 0);
     value2 = Convert.ToDouble(row["value2"]);
     sum +=  (double)Global.Calculate(value1 / value2, 2);
 }

But of course, it is still not clear and I am doing something wrong.但是,当然,它仍然不清楚,我做错了什么。 I need to check all values if they are DBNull and after that I need to convert them.我需要检查所有值是否为DBNull ,然后我需要转换它们。 Any ideas how can I improve this type of code?有什么想法可以改进这种类型的代码吗? It's all around my code:)一切都围绕着我的代码:)

Is there a good way to handle SQL data? SQL数据有没有好的处理方式?

Don't think in terms of "convert".不要考虑“转换”。 These objects are already the types you want;这些对象已经是你想要的类型; it's just the ADO.Net library can't know in advance what type to use.只是 ADO.Net 库无法提前知道使用什么类型。 So instead of a conversion, which can be relatively slow, you need a cast .因此,您需要一个转换,而不是一个相对较慢的转换

Additionally, in general you don't want to think initially in terms of individual columns.此外,一般来说,您最初不希望根据各个列来考虑。 Instead, define a class object to represent each row.相反,定义一个class object 来表示每一行。 Then create a function that accepts a DataRow as an argument and returns an instance of this new class as a result.然后创建一个 function 接受一个DataRow作为参数,并返回这个新的 class 的一个实例作为结果。 This function will need to know what to do with individual columns, but the larger foreach loop (or similar) should just be calling this function.这个 function需要知道如何处理各个列,但更大的foreach循环(或类似循环)应该只是调用这个 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM