我有一個數據集應該只有一個值,什麼是最好的方式獲得單個值出來,併成爲一個整數?從數據集中獲取單個值的最佳方式是什麼?
4
A
回答
6
// setup sql command and sql connection etc first...
int count = (int) cmd.ExecuteScalar();
0
最好的辦法是不要寫在數據集中的單個值。
,但如果你不能避免它:
try
{
//if the value is coming back as string
int value1 = Int32.Parse(ds.Tables[0].Rows[0][0].ToString());
//if the value is already an integer
int value2 = (int)ds.Tables[0].Rows[0][0];
}
catch(Exception ex)
{
throw new Exception("You do not have even a single value in the DataSet or its not an integer!", ex);
}
1
if (ds.Tables[0].Rows.Count > 0) {
int i = Convert.ToInt32(ds.Tables[0].Rows[0]["colname"]);
}
+0
雖然這段代碼可能會回答這個問題,但提供關於爲什麼和/或代碼如何回答這個問題的附加上下文會提高它的長期價值。 –
0
,你可以這樣做:
dt = ds.Tables["TableName"];
Convert.ToInt32(dt.Rows[rowNumber]["ColumnName"].ToString());
0
你可以做這樣的...
int myVar =
Convert.ToInt32(dsMyDataSet.Tables["MyTable"].Rows[intRowPos]["MyColumn"].Tostring());
+0
沒有從對象轉換爲decimal或int –
4
見C#3.0'擴展方法'的新特性您可以爲任何類定義您自己的擴展方法。 例如:
namespace MyEx;
public static class MyExtensions
{
public static object SingleValue(this DataSet ds)
{
return ds.Tables[0].Rows[0][0];
}
}
後,您可以使用它:
using MyEx;
public class Class1
{
public void Test()
{
DataSet ds = new DataSet();
object value = ds.SingleValue();
}
}
相關問題
- 1. 從jqGrid單元獲取數據的最佳方式是什麼?
- 2. 從常規集中提取單個值的最佳方式是什麼?
- 3. 從app.config獲取數據的最佳方式是什麼?
- 4. 從detailViewController獲取布爾值的最佳方式是什麼?
- 5. 與關係獲取數據的最佳方式是什麼?
- 6. PHP:獲取$ _POST數據的最佳方式是什麼?
- 7. 在strings.xml中獲取attrubute值的最佳方式是什麼?
- 8. 從Zillow刮取數據的最佳方式是什麼?
- 9. 什麼是使用JavaScript獲取和設置單個cookie值的「最佳」方式
- 10. 什麼是實時從數據庫中獲取數據的最佳方法?
- 11. 從Twitter獲取我想要的數據的最佳方式是什麼?
- 12. 從PHP中的$ _POST對象獲取鍵/值的最佳方式是什麼?
- 13. 從Eclipse的asyncExec中獲取返回值的最佳方式是什麼?
- 14. 從PHP獲取數據到iOS應用程序的最佳方式是什麼?
- 15. 從NHibernate獲取聚合結果的最佳方式是什麼?
- 16. 廚師從用戶獲取UID的最佳方式是什麼?
- 17. 從單詞組中獲取電子郵件ID的最佳方式是什麼?
- 18. 什麼是從vb.net獲取數據的最快方式?
- 19. 爲(從)翻譯存儲集中數據的最佳方式是什麼?
- 20. 從數據庫中獲取數據的最佳方式
- 21. 獲取Perl數組的最後N個元素的最佳方式是什麼?
- 22. 輪詢數據庫獲取值的最佳選擇是什麼?
- 23. 什麼是優化模式以獲取考勤數據的最佳方式
- 24. 在數據集中存儲Delphi集合的最佳方式是什麼?
- 25. 抓取網站數據(內容)的最佳方式是什麼?
- 26. 什麼是在OnInit()中獲取控件值的最佳方法?
- 27. 在django中獲取row_num的最佳方式是什麼?
- 28. 在PHP中獲取HashTable的最佳方式是什麼?
- 29. 從android網站獲取數據的最佳選擇是什麼?
- 30. 從silverlight訪問oracle數據庫的最佳方式是什麼?
這比使用一個數據集就是我想要做的更好,好:) – Steve
+1,好趕上! – sll
+1:Linq to SQL是另一個類似的選擇。 –