Link to home
Start Free TrialLog in
Avatar of andyw27
andyw27

asked on

Copy rows from Datatable

Hi,

If I have datatable that looks like this:

Col 1      Col 3      Col 4      Col 5
1001      906      581      403
1001      538      822      330
1001      354      837      982
1001      649      861      955
1001      499      673      286
2005      803      899      594
2005      994      385      463
2005      279      272      141
3006      275      945      396
3006      448      392      180
3006      286      842      678
3006      802      718      880

(The real world example has thousands of records.)

I need to create a function that accepts an int (in this case Col 1) and returns a new datatable contains just the rows the match col 1.  For example if I passed 2005 I would expect the new datatable to look like this:

2005      803      899      594
2005      994      385      463
2005      279      272      141


Looking for the most efficient means of doing this?
ASKER CERTIFIED SOLUTION
Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I think you could use something like this:

private DataTable GetDTByFilter(DataTable dt, int col, int match)
        {
            string expression;

            expression = "Col" + col.ToString() + "=" + match.ToString();
            DataRow[] foundRows;

            foundRows = dt.Select(expression);

            return (foundRows.CopyToDataTable());
        }
Try this i hope it will help you.

private void button1_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("Col1"));
            dt.Columns.Add(new DataColumn("Col2"));
            dt.Columns.Add(new DataColumn("Col3"));

            dt.Rows.Add(new object[] { 2005, 803, 899 });


            for (int i = 0; i < 4; i++)
            {
                //loop here to calculate or get values.
                AddToDataTable(2006, ref  dt);
            }

        }
       
        private void AddToDataTable(int colValue, ref DataTable dt)
        {
            //do calculations here for 830,900 values
            string colValues = string.Format("{0},{1},{2}", colValue, 830, 900);
            dt.Rows.Add(colValues.Split(new char[] { ',' }));
        }