[英]SqlDataReader - How to convert the current row to a dictionary
有沒有一種簡單的方法將SqlDataReader的當前行的所有列轉換為字典?
using (SqlDataReader opReader = command.ExecuteReader())
{
// Convert the current row to a dictionary
}
謝謝
您可以使用LINQ:
return Enumerable.Range(0, reader.FieldCount)
.ToDictionary(reader.GetName, reader.GetValue);
比這更容易?:
// Need to read the row in, usually in a while ( opReader.Read ) {} loop...
opReader.Read();
// Convert current row into a dictionary
Dictionary<string, object> dict = new Dictionary<string, object>();
for( int lp = 0 ; lp < opReader.FieldCount ; lp++ ) {
dict.Add(opReader.GetName(lp), opReader.GetValue(lp));
}
我仍然不確定為什么你需要從一種類型的集合到另一種集合的這種特殊轉換。
我在2016年3月9日遇到了這個問題,最后使用了SLaks提供的答案。 但是,我需要稍微修改它為:
dataRowDictionary = Enumerable.Range(0, reader.FieldCount).ToDictionary(i => reader.GetName(i), i=> reader.GetValue(i).ToString());
我從StackOverflow問題中找到了指導: 將dataReader轉換為Dictionary
它已經是IDataRecord
。
這應該給你幾乎與字典相同的訪問權限(按鍵)。 由於行通常不會有多個列,因此查找的性能不應該那么不同。 唯一重要的區別是“有效負載”的類型,即使你的字典必須使用對象作為值類型,所以我給IDataRecord邊緣。
GetValues方法接受並放入1D數組中的所有值。
這有幫助嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.