# dataTable 运算的问题!路过的大侠帮忙看下吧!

0

dt列 name相等 那么下一条减去上一条 差 值相加 如果如果差值大于5或者小于0过滤

(4-1)+（79-78）这样的格式

```  DataTable dt = new DataTable();
DataRow row = dt.NewRow();
row[0] = "1";
row[1] = "张三";
row[2] = "1";
row[3] = DateTime.Now;

DataRow row1 = dt.NewRow();
row1[0] = "1";
row1[1] = "张三";
row1[2] = "4";

DataRow row2 = dt.NewRow();
row2[0] = "1";
row2[1] = "张三";
row2[2] = "78";

DataRow row21 = dt.NewRow();
row21[0] = "1";
row21[1] = "张三";
row21[2] = "79";

DataRow rowt = dt.NewRow();
rowt[0] = "1";
rowt[1] = "张三";
rowt[2] = "80";

DataRow row3 = dt.NewRow();
row3[0] = "2";
row3[1] = "李四";
row3[2] = "2";
row3[3] = DateTime.Now;

DataRow row4 = dt.NewRow();
row4[0] = "2";
row4[1] = "李四";
row4[2] = "5";

DataRow d = dt.NewRow();
d[0] = "2";
d[1] = "李四";
d[2] = "5";

DataRow row5 = dt.NewRow();
row5[0] = "3";
row5[1] = "王五";
row5[2] = "3";

var sum = 0;
var resultDt = new DataTable();
var isFlag = true;
var fistMile = "";
for (int i = 0; i < dt.Rows.Count - 1; i++)
{
var nowValue = dt.Rows[i]["value"].ToString();
var nextValue = dt.Rows[i + 1]["value"].ToString();
if (dt.Rows[i]["Name"] == dt.Rows[i + 1]["Name"])
{
//如果下一条时间小于上一条时间终止
if (DateTime.Parse(dt.Rows[i + 1]["Time"].ToString()) < DateTime.Parse(dt.Rows[i]["Time"].ToString())) continue;

//差值累加 如果大于5 并且小于过滤掉
var tempSum = int.Parse(nextValue) - int.Parse(nowValue);
if (tempSum < 5 && tempSum > 0)
{
//第一次的值
if (fistMile=="")
{
fistMile = nowValue;
}
sum += tempSum;
isFlag = false;
}
}
//name不相等 并且 isFlag为flase 代表当前name相同的有多条(这里过滤王五)
if (dt.Rows[i]["Name"] != dt.Rows[i + 1]["Name"])
{
if (!isFlag)
{
}
fistMile = "";
sum = 0;
}
}```

s_p | 菜鸟二级 | 园豆：295

0
```foreach (var g in dt.Rows.Cast<DataRow>().GroupBy(x => x["Name"]))
{
int sum = 0;
var gList = g.ToList();
if (gList.Count < 2)
{
continue;
}
for (var i = 0; i < gList.Count - 1; i++)
{
if (Convert.ToDateTime(gList[i + 1]["Time"]) < Convert.ToDateTime(gList[i]["Time"])) continue;
var x = Convert.ToInt32(gList[i + 1]["value"]) - Convert.ToInt32(gList[i]["value"]);
if (x > 0 && x < 5)
{
sum += x;
}
}
resultDt.Rows.Add(gList[0]["csID"], g.Key, gList[0]["value"], gList[gList.Count - 1]["value"], sum);
}```

`还是建议用强实体。`

0

您需要登录以后才能回答，未注册用户请先注册