Thursday, May 12, 2016

Find row in datatable linq using C#






  • Add a reference to the System.Data.DataSetExtensions.This is usually added by default.
  • Add the namespace System.Linq 

Create Datatable


        public static DataTable GetTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Id", typeof(int));
            dt.Columns.Add("Name", typeof(string));

            dt.Rows.Add("C#", 1);
            dt.Rows.Add("Asp.net", 2);
            dt.Rows.Add("SqlServer", 3);

            return dt;
        }


Find in datatable

  DataTable dt = GetTable();
var dataRow = dt.AsEnumerable().Where(x => x.Field("Name") == "C#").FirstOrDefault();

                    if (dataRow != null)
                    {
                        int Id = Convert.ToInt32(dataRow["Id"]);
                    }

No comments:

Post a Comment