2016-05-29 22 views
0

私はこのようなテーブルを持っている:DataGridviewから各アイテムの小計を計算する方法は?

NAME ITEM COUNT 
a  x  2 
a  y  1 
b  x  3 
c  z  1 
d  y  1 
d  y  1 

私は

double sum = 0; 
for (int i = 0; i < dataGridView1.Rows.Count; ++i) 
    { 
     sum += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value); 
    } 

はどのようにして個別に各項目の合計を計算することができ、合計を計算するためにこのコードを使用している、結果は次のようになります。

x=5 
y=3 
z=1 
+2

あなたは、C#ソリューションまたはSQL 1をお探しですか?それがSQLソリューションであれば、どのデータベースを使用していますか? –

+0

http://stackoverflow.com/questions/18417333/how-we-add-numaric-value-of-multiple-cell-of-a-datagridview/18418027#18418027 – SK2185

+0

@Senthilkumar、前にリンクについて少し説明してくださいそれを埋める。 –

答えて

0

次の手順に従います。

1)データグリッド。

2)同様の項目(x、y、zなど)をループ内で識別し、それらを合計します。

int SumX=0; 
int SumY=0; 
int SumZ=0; 
for (int i = 0; i < dataGridView1.Rows.Count; ++i) 
{ 
if(Convert.ToString(dataGridView1.Rows[i].Cells[1].Value == "x") 
    sumX += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value); 
else if(Convert.ToString(dataGridView1.Rows[i].Cells[1].Value == "y") 
    sumY += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value); 
else if(Convert.ToString(dataGridView1.Rows[i].Cells[1].Value == "z") 
    sumZ += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value); 
} 

ここにはexampleがあります。

LINQクエリを使用すると、それはかなり簡単です。

int SumX = dataGridView1.Rows.Cast<DataGridViewRow>() 
        .Where(r=> Convert.ToInt32(r.Cells["Item"].Value) == "x") 
        .Sum(t=> Convert.ToInt32(t.Cells["Count"].Value)); 

編集

本当にこの総和は、動的にしたいなら、あなたはここにthis.Basicallyような何かを行うことができ、同一の項目を(s)を追跡して、対応を合計する辞書ですカウント。

Dictionary<string, int> dic = new Dictionary<string, int>(); 
    string item = null; 
    for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++) 
    { 
      item = dataGridView1.Rows[i].Cells[1].Value.ToString(); 
      if (!dic.ContainsKey(item)) 
      { 
       dic.Add(item, Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value); 
      } 
      else 
      { 
       dic[item] += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value); 
      } 

    } 

これで、辞書をループしてユニークなアイテム数を取得できます。

foreach (KeyValuePair<string, int> keyvalue in dic) 
    { 
     //get it here 
    }  

希望します。

+0

'Z'列はどうですか? –

+0

「ITEM」列にさらに多くのケースがある場合はどうなりますか?私はあなたが 'グループby 'を使うべきだと思います。 –

+0

@SiyavashHamdi正確なユースケースOP提供に基づいて回答を掲載しました。あなたが言っているのはより実践的なシナリオです。グループバイスと合計はデータソースレベルに適用する必要があります。 –

0

は合計でグループ化された項目の辞書を取得するには、以下の方法を試してみてください。

private Dictionary<string, int> GetSummation() 
{ 
    var kvp = new List<KeyValuePair<string, int>>(); 

    for (var i = 0; i < GridView1.Rows.Count; i++) 
    { 
     var item = GridView1.Rows[i].Cells[1].Text.Trim(); 
     var count = Convert.ToInt32(GridView1.Rows[i].Cells[2].Text); 

     kvp.Add(new KeyValuePair<string, int>(item, count)); 
    } 

    return kvp.GroupBy(k => k.Key).ToDictionary(g => g.Key, g => g.Sum(x => x.Value)); 
} 
関連する問題