2011-12-21 105 views
1

我有問題開發Windows移動應用程序使用C#,我試圖與3查詢工作。 我想收集所有結果查詢到詞典。在字典中存儲查詢結果

我可以收集它沒有循環?

像這樣我的代碼:

string query= "select distinct nameProduct, price from product"; 
SqlCeCommand cmd = new SqlCeCommand(sql, dbConn); 
Dictionary production = new Dictionary<string, int>(); 

如何設置這個產量從我的查詢,becausei有一個過程3這樣的查詢和數據是超過10000。當我嘗試這個,我得到錯誤「{」沒有數據存在的行/列。「}」但實際上,當我嘗試在sql服務器中的查詢仍然運行良好。該行中的錯誤:production [(string)reader [「nameProduct」]] =(int)reader [「price」];

@Johnny: 不幸的是,這個項目在VS2005中構建,不支持union和join語句。

+1

你的問題來從數據庫和存儲數據的數據是很不清楚 – 2011-12-21 02:25:26

+0

如果這是10K時間找出一些不同的東西。 – Will 2011-12-21 02:52:39

+0

您如何看待(a,11.0)(a,12.0) – shenhengbin 2011-12-21 03:04:05

回答

2
Dictionary production = new Dictionary<string, int>(); 
string query= "select distinct nameProduct, price from product"; 
using (SqlCeCommand cmd = new SqlCeCommand(sql, dbConn)) 
{ 
    using (var reader = cmd.ExecuteReader()) 
    { 
     while (reader.Read()) 
     { 
      production[(string)reader["nameProduct"]] = (int)reader["price"]; 
     } 
    } 
} 

沒有循環。注意:我還沒有嘗試過:

production = 
    reader.Cast<IDataRecord>() 
      .ToDictionary(
       record => (string)record["nameProduct"], 
       record => (int)record["price"]); 
+0

OP _asks_如果他沒有循環就可以做到。 – 2011-12-21 02:38:39

+0

不可能沒有循環,儘管你可以將循環隱藏'ToDictionary()'。 – Sjoerd 2011-12-21 03:03:44

+1

雖然是一個循環,ToDictionary也是如此。正確的答案是「不,你不能這樣做。」從你的水果碗中取出3個蘋果的唯一方法就是走到櫃檯旁,數着它們,排除桔子和香蕉,只抓3個蘋果。這看起來不是什麼大不了的事,因爲人們知道3個蘋果而沒有考慮它。但是即使在潛意識層面上,計數和排除的過程仍然需要發生。你無法避免它,也不可能在沒有經過所有步驟的情況下實現手中的3個蘋果。 – Krythic 2018-02-25 08:26:01

1

您可將數據表(使用DataAdapter.Fill方法方法來填充數據表),導致到百科。

string query= "select distinct nameProduct, price from product"; 
SqlCeConnection conn = new SqlCeConnection("Data Source = your file.sdf"); 

SqlCeCommand selectCmd = conn.CreateCommand(); 
selectCmd.CommandText = query; 

SqlCeDataAdapter adp = new SqlCeDataAdapter(selectCmd); 
DataTable dt=new DataTable(); 
adp.Fill(dt); 

Dictionary<string, int> result = (from row in dt.AsEnumerable() 
          select new KeyValuePair<string, int> 
          (row.Field<string>("nameProduct"), row.Field<int>("price"))) 
          .ToDictionary(p=>p.Key,p=>p.Value); 

foreach (var t in result) 
    { 
    Console.WriteLine(t.Key + " " + t.Value); 
    } 
+0

當我嘗試這個,我得到錯誤「{」沒有數據存在的行/列。「}」 但實際上,當我嘗試在sql服務器仍然運行良好的查詢。 錯誤行: production [(string)reader [「nameProduct」]] =(int)reader [「price」]; – indi60 2011-12-21 03:36:01

0

幾點。

1.我認爲你可以在你的查詢中使用「union all」。 2.如果您有超過10000行的記錄,尤其是在移動設備上,我建議您只加載所需的數據,並且可以在一個屏幕上顯示,而不是全部讀取。

2

這是一個簡單的方式解釋

Dictionary<int, string>emp = new Dictionary<int, string>(); 
OleDbCommand cmd = new OleDbCommand("select empId,Name from Employee where ORDER BY empId DESC", con); 
OleDbDataReader dr = cmd.ExecuteReader(); 

if (dr.HasRows) 
{ 
    while (dr.Read()) 
    { 
     emp.Add(Convert.ToInt32(dr["empId"]), dr["Name"].ToString());     
    }      
} 

foreach (KeyValuePair<int, string> em in emp) 
{ 
    Console.WriteLine(em.Key.ToString() + " = " + em.Value); 
} 
相關問題