Search code examples
c#datatabledatatables

C#/DataTable - Getting datable first row & last row value base on the column value


I want to get the first row & last row of the DataTable base on the column value.

StoreNo   ORNo
1         AAA
2         BBB
1         CCC
2         DDD
1         EEE
2         FFF

I want to get the AAA & EEE because it is the first and last ORNo of the StoreNo

This is my code:

 for (int i = 0; i < dataTable.Rows.Count; i++)
 {
     if (dataTable.Rows[i]["StoreNo"].ToString().Equals("1"))
        {
            firstID = dataTable.Rows[0]["ORNo"].ToString();
        }
     if (dataTable.Rows[i]["StoreNo"].ToString().Equals("1"))
        {
            lastID = dataTable.Rows[dataTable.Rows.Count - 1]["ORNo"].ToString();
        }
 }

I always get AAA & FFF.

Thanks!


Solution

  • You can use linq instead of for loop,

    Before you begin, make sure that the following lines are at the top of your code,

    using System;
    using System.Collections.Generic;
    using System.Linq;
    

    then try this code,

    var list = dataTable.AsEnumerable().Where(row => row["StoreNo"].ToString() == "1");
    firstID = list.FirstOrDefault()["ORNo"];
    lastID = list.LastOrDefault()["ORNo"];