locked
how to find max value from two different columns from two table using LINQ C# RRS feed

  • Question

  • User-1024101449 posted

    Hi,

    how to find max value from two different columns from two table after subtracting from column A1 (table A) and ColumnA1(Table-B)

    for example, i have two tables.

    i want to subtract from table A and Table B of (coulmn A1).

    Table-A Table-B
    A1 B1 A1 B1
    2 2 7 2
    4 4 1 4
    6 6 5 6
    9 9 6 9
    6 10 10 10
    7 11 11 11

    after subtracting result would be below

    -5
    3
    1
    3
    -4
    -4

    finally i want to get max value in the above list after convering minus valus.

    Final output will be = 5

    how to write in linq to compare and subtract two columns..?

    Thursday, June 15, 2017 11:28 AM

Answers

  • User-1838255255 posted

    Hi gani7787,

    According to your needs, I make a sample, please check:

    public partial class Page470 : System.Web.UI.Page
        {
            DataTable table = new DataTable("TableA");
            DataTable DT = new DataTable("TableB");
    
            protected void Page_Load(object sender, EventArgs e)
            {
                table.Columns.Add("A1", typeof(int));
                table.Columns.Add("B1", typeof(int));
    
                // Here we add five DataRows.
                table.Rows.Add(2, 2);
                table.Rows.Add(4, 4);
                table.Rows.Add(6, 6);
                table.Rows.Add(9, 9);
                table.Rows.Add(6, 10);
                table.Rows.Add(7, 11);
    
                DT.Columns.Add("A1", typeof(int));
                DT.Columns.Add("B1", typeof(int));
    
                // Here we add five DataRows.
                DT.Rows.Add(7, 2);
                DT.Rows.Add(1, 4);
                DT.Rows.Add(5, 6);
                DT.Rows.Add(6, 9);
                DT.Rows.Add(10, 10);
                DT.Rows.Add(11, 11);
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                int[] TableA = table.AsEnumerable().Select(s => s.Field<int>("A1")).ToArray<int>();
                int[] TableB = DT.AsEnumerable().Select(s => s.Field<int>("A1")).ToArray<int>();
                int[] array = new int[6];
    
                for (int i = 0; i < TableA.Length; i++)
                {
                    array[i] = TableA[i] - TableB[i];
                }
    
                foreach (var item in array)
                {
                    Response.Write(item + "<br/>");
                }
                Response.Write("<br/>"+"The MAX value is: "+array.Max());
            }

    Result:

    Best Regards,

    Eric Du

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, June 16, 2017 6:18 AM