我有一个datagridview,其中填充了来自.csv文件的记录(大约30k记录,其中30-40个唯一ID - 取决于文件)。它看起来像这样:
现在我的问题是如何按ID总结这些列?或者也许有一种方法可以直接将已经上升的值放到datagridview中?
private void dropListBox_DragDrop(object sender, DragEventArgs e)
{
data= new List<Raport>();
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
{
var nameOnly = System.IO.Path.GetFileName(file);
dropListBox.Items.Clear();
dropListBox.Items.Add(nameOnly);
dataGridView1.Rows.Clear();
string[] readText = File.ReadAllLines(file, Encoding.GetEncoding("Windows-1250"));
int i = 0;
foreach (string line in readText)
{
if (i++ == 0) continue;
var values = line.Split(';');
string a= values[0];
string b= values[1];
string c= values[2];
string user = values[3];
int xValues= int.Parse(values[4]);
int yValues= int.Parse(values[5]);
double d= double.Parse(values[6]);
string e= values[7];
string f= values[8];
string g= values[9];
string h= values[10];
double i= double.Parse(values[11]);
string j= values[12];
Raport Raport = new Raport(
a,
b,
c,
user,
xValues,
yValues,
d,
e,
f,
g,
h,
i,
j);
data.Add(Raport);
dataGridView1.Rows.Add(Raport.user, Raport.xValues, Raport.yValues, "8", "8");
这是我的代码。最后两列并不重要(它总是用固定值填充)
任何建议都将不胜感激。
应该是这样的
John | 5 | 4
Carl | 3 | 1
John | 1 | 6
Carl | 4 | 1
然后
John | 6 | 10
Carl | 7 | 2
Raport课程的结构
class Raport
{
public readonly string a;
public readonly string b;
public readonly string c;
public readonly string user;
public readonly int xValue;
public readonly int yValue;
public readonly double d;
public readonly string e;
public readonly string f;
public readonly string g;
public readonly string h;
public readonly double i;
public readonly string j;
public Raport(
string a,
string b,
string c,
string user,
int xValue,
int yValue,
double d,
string e,
string f,
string g,
string h,
double i,
string j)
{
this.a= a;
this.b= b;
this.c= c;
this.user= user;
this.xValue= xValue;
this.yValue= yValue;
this.d= d;
this.e= e;
this.f= f;
this.g= g;
this.h= h;
this.i= i;
this.j= j;
}
public Raport()
{
}
public override string ToString()
{
return a+ " ; " +
b+ " ; " +
c+ " ; " +
user+ " ; " +
xValue+ " ; " +
yValue+ " ; " +
d+ " ; " +
e+ " ; " +
f+ " ; " +
g+ " ; " +
h+ " ; " +
i+ " ; " +
j;
}
}
}
答案 0 :(得分:0)
目前,您已将每个Raport
对象添加到列表和 DataGridView中:
data= new List<Raport>();
// ...
data.Add(Raport);
dataGridView1.Rows.Add(Raport.user, Raport.xValues, Raport.yValues, "8", "8");
您可以利用此列表和LINQ利用user
属性对对象进行分组,并将其他两个所需属性as seen here相加。这将存储到另一个列表中,然后可以用它来填充DataGridView:
var summedData = data.GroupBy(r => new { r.user })
.Select(r => new Raport()
{
user = r.Key.user,
xValue = r.Sum(innerR => innerR.xValue),
yValue = r.Sum(innerR => innerR.yValue)
}
);
然后,不是添加在创建原始Raport
列表期间创建的每个data
,而是循环遍历新的汇总列表:
foreach (Raport raport in summedData)
{
dataGridView1.Rows.Add(raport.user, raport.xValues, raport.yValues, "8", "8");
}