SqlDataReader の現在の行のすべての列を辞書に変換する簡単な方法はありますか?
using (SqlDataReader opReader = command.ExecuteReader())
{
// 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 の質問からガイダンスを見つけました: convert dataReader to Dictionary
それはすでにIDataRecord
です。
これにより、辞書とほぼ同じアクセス (キーによる) が得られるはずです。通常、行には少数の列しかないため、ルックアップのパフォーマンスはそれほど変わらないはずです。唯一の重要な違いは「ペイロード」の型です。それでも、辞書は値の型にオブジェクトを使用する必要があるため、IDataRecord に優位性を与えます。
GetValues メソッドは、1D 配列内のすべての値を受け入れて挿入します。
それは役に立ちますか?