I have a datatable in Winforms.

I am currently trying to find the max and min values for each of the columns for each row. My table layout is like this

A  | B |  C | D | E |
---+---+----+---+---+
5  | 2 | 3  | 4 |  3

The end goal is to have a function that would caculate
Max(A,B,C,D) - Min(A,B,C,D)

This works

  dt.Columns.Add("Function Column", typeof(Double), "A + B + C + D"); 

This returns that Max value for the entire table

dt.Columns.Add("Function Column", typeof(Double), "Max(A)"); 

How do I get the max and min values of each row so I can do my caculation ?

The DataRow class has an ItemArray property. Using this you can use Min and Max extensions to get what you want. If you don't want the whole row, there are other extensions available that can help you select only certain columns.

Something like this:

    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[]
    {
        new DataColumn("A", typeof(double)),
        new DataColumn("B", typeof(double)),
        new DataColumn("C", typeof(double)),
        new DataColumn("D", typeof(double)),
        new DataColumn("E", typeof(double)),
    });
    DataRow dr = dt.NewRow();
    dr.ItemArray = new object[]{ 5,2,3,4,6};
    var max = dr.ItemArray.Max(x => (double)x);
    var partMax = dr.ItemArray.Take(4).Max(x => (double)x);

Thanks for your help, I for got to state that this is a form and I would like to do it dymanically on input. Where column E would have the expression function.

To simplfy :

How do I grab each cell value on a row dymanically so I can use it in a function.

I don't think something like that is allowed. What you can do is have an extra column in your datatable and add the values after you've populated it from your data source.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.