1

次の行を返すテーブルがあります。

ID (integer)   PRICE (decimal)
106                 5.2
106                 6.7
107                 9.2
107                 8.3
107                 3.2

このテーブルの値を次のように変換する必要があります。

106, (5.2, 6.7)
107, (9.2, 8.3, 3.2)

この場合、これは ですDictionary<int, List<decimal>>が、辞書である必要はありません。必要に応じて変更できます。

ID の数とそれに対応する価格は固定されていません (したがって、このリストには 108 個あり、1 つ以上の価格を持つことができます)。

以下は私がやったことです:

var retVal = new Dictionary<int, List<decimal>>();
var dbRow = new List<decimal>();
var itemsPerRow = new List<List<decimal>>();

....

//loop the table
using (var dr = cmd.ExecuteReader())
{
    while (dr.Read())
    {
        dbRow.Add(int.Parse(dr["ID"].ToString()));
        dbRow.Add(decimal.Parse(dr["PRICE"].ToString()));
        itemsPerRow.Add(dbRow);
    }        
}

//get the distinct ID's 
var gb = itemsPerRow.GroupBy(x => x[0]).Select(x => x.Key);

foreach (var row in gb)
{
    if (!retVal.ContainsKey((int) row))
    {
        IEnumerable<decimal> ratesForRow = itemsPerRow.Where(x => x.Contains(row)).Select(x => x[1]);
        retVal.Add((int) row, ratesForRow.ToList());
    }
}

これは機能しますが、あまり単純ではないようです。満足できないのは、データベースの結果をループし、リストを作成してから、リストを再度ループしていることです。また、リストは小数を含むと宣言されていますが、ID 列は int です。だから私はそれをintにキャストしなければなりません。これで問題ありませんか、それとも別の方法がありますか?

ありがとう

4

2 に答える 2

1

1 つのループで直接実行できます。

  Dictionary<int, List<Decimal>> result = new Dictionary<int, List<Decimal>>();

  using (var reader = cmd.ExecuteReader()) {
    while (reader.Read()) {
      int id = int.Parse(reader["ID"].ToString());
      Decimal price = Decimal.Parse(reader["PRICE"].ToString());

      List<Decimal> list;

      if (result.TryGetValue(id, out list))    
        list.Add(price);
      else 
        result.Add(id, new List<Decimal> {price});
    }
  }
于 2013-07-19T11:56:15.663 に答える
1

どれどれ。まず、必要なリストは 1 つだけです。

var tempResults = Enumerable.Empty<KeyValuePair<int, decimal>>().ToList();
using (var dr = cmd.ExecuteReader())
while (dr.Read())
     tempResults.Add(new KeyValuePair<int, decimal> 
            { Key = int.Parse(dr["ID"].ToString()), 
              Value = decimal.Parse(dr["PRICE"].ToString()) });

その場合、処理はかなり単純です。

return tempResults.GroupBy(k => k.Key).ToDictionary(g => g.Key, g => g.ToList());
于 2013-07-19T11:46:33.897 に答える