遍历DataTable行以根据下一行中的值获取子集 [英] Loop through DataTable rows getting subset based on values in the next row
问题描述
我正在从Excel将文件读取到DataTable中,其结构如下:
日期名称金额拆分
2014年1月1日约翰·史密斯(John Smith)$ 150.00
2014年1月1日,约翰·史密斯(John Smith),75.00美元
2014年1月1日,鲍勃·史密斯(Bob Smith)$ 25.00
2014年1月1日,约翰·史密斯(John Smith)$ 50.00
这种结构的方式是,$ 150行是一个记录,而其余三行是一个记录,并且两个拆分的金额总计为$ 75.00.我需要对单行和多行进行不同的处理,因此我编写了一个函数来添加具有ID的列,如下所示:
int countID = 0 ;
for ( int index = 0 ; index < dataGridView1.Rows.Count; index ++)
{
如果(索引+ 1 != dataGridView1.Rows.Count)
如果(dataGridView1.Rows [index] .Cells [" ].Value == " ].Value.ToString()== " )
countID ++;
dataGridView1.Rows [index] .Cells [" ].Value = countID.ToString();
}
这使我得到相同行的相同编号,但是我一直认为可能有更好的方法遍历这些行,可能使用LINQ或其他某种方式(我的LINQ知识非常基础). ="h2_lin">解决方案
150.00 2014年1月1日,约翰·史密斯(John Smith)
75.00 2014年1月1日Bob Smith
25.00 2014年1月1日,约翰·史密斯(John Smith)
I am reading a file into a DataTable from Excel, which is structured like so:
Date Name Amount Split
01/01/2014 John Smith $150.00
01/01/2014 John Smith $75.00
01/01/2014 Bob Smith $25.00
01/01/2014 John Smith $50.00
The way that this is structured, the $150 line is one record, while the remaining three rows are one record as well as the two split amounts total to the $75.00. I need to process the single rows differently than the multi-line rows, so I wrote a function to go through and add a column with an ID like so:
int countID = 0;
for (int index = 0; index < dataGridView1.Rows.Count; index++)
{
if (index + 1 != dataGridView1.Rows.Count)
if (dataGridView1.Rows[index].Cells["Split"].Value == null ||
dataGridView1.Rows[index].Cells["Split"].Value.ToString() == "")
countID++;
dataGridView1.Rows[index].Cells["ID"].Value = countID.ToString();
}
And this get''s me the same number for the rows that are the same, however I was thinking there might be a better way to loop through these, possibly using LINQ or something (my LINQ knowledge is very basic).
150.00 01/01/2014 John Smith
75.00 01/01/2014 Bob Smith
25.00 01/01/2014 John Smith
这篇关于遍历DataTable行以根据下一行中的值获取子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!