开发者

building tab delimited files from one datatable

i have a datatable:

        var dt = new DataTable();
        dt.Columns.Add(new DataColumn("specimen", typeof(string)));
        dt.Columns.Add(new DataColumn("batch", typeof(string)));
        dt.Columns.Add(new DataColumn("position", typeof(string)));

the data looks something like this inside of it:

Spec. ID    Batch/Pos.  position
AA00721 16785   3
AA00722 16785   2
AA00734 16785   3
AA00735 16860   6
AA00737 16862   4
AA00738 16860   7
AA00739 16863   5
AA00740 16860   9
AA00741 16861   7
AA00742 16861   0
AA00743 16861   5

for each unique batch, i need to create a file with all the specIDs and po开发者_开发技巧sitions.

for example file 16785.txt would look like this:

AA00721 3
AA00722 2
AA00734 3

how would i loop through this datatable to create separate files>? please assume that the batch numbers are not sorted


If you would like to utilize a LINQ method, I would group your data on the batch and then just iterate through the groups.

var groupedData = from DataRow row in dt.Rows
                    let specimen = row["specimen"].ToString()
                    let batch = row["batch"].ToString()
                    let position = row["position"].ToString()
                    group new { specimen, position } by batch;

foreach (var dataGroup in groupedData)
{
    string fileName = string.Format(@"C:\Temp\{0}.txt", dataGroup.Key); // construct filename based on batch?
    using (StreamWriter writer = new StreamWriter(fileName))
    {
        foreach (var item in dataGroup)
        {
            writer.WriteLine("{0}\t{1}", item.specimen, item.position);
        }
    }
}


Create a dataview and sort it based on the batch number. Then iterate thru each row and write the specid and postion to a file. Store the bactch number outside the loop. Create new file if the everytime the bacth number changes. There may be other ways to do it but I find this one straightforward.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜