Linq query for select single value from data table when matched condition true.

(a)This method return DataTable.

    private DataTable datatable1()
        {
            DataTable _dt = new DataTable();
            _dt.Columns.Add("id", typeof(int));
            _dt.Columns.Add("Name", typeof(string));
            _dt.Rows.Add(1, "Priti");
            _dt.Rows.Add(2, "Priya");
            _dt.Rows.Add(3, "Neha");
            _dt.Rows.Add(4, "aman");
            _dt.Rows.Add(5, "ram");
            _dt.Rows.Add(6, "sita");
            return _dt;
        }

(b) Three different query for this result.

(a) string s = (datatable1().AsEnumerable().Where(p => p["id"].ToString() == "1").Select(p => p["Name"].ToString())).FirstOrDefault();

OR
     (b)  string s1 = (datatable1().AsEnumerable().Where(p => p.Field<int>("id") == 1).Select(p => p.Field<string>("Name"))).FirstOrDefault();
                                                                              OR

 (c)string d1 = (datatable1().AsEnumerable().FirstOrDefault(p => p["id"].ToString() == "1")["Name"].ToString());
Author

Priti Kumari

I am technical blogger.I blogs at www.c-Sharpcorner.com and https://aspdotnetmyblog.blogspot.in/.

2 comments:

  1. It is really a great work and the way in which u r sharing the knowledge is excellent.
    Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article. Dot Net Training in chennai | dot net training institute in velachery

    ReplyDelete
  2. Linq query for select single value from data table when matched condition true.Thanks for your valuable information. dot net training and placement in chennai | dot net training center in chennai

    ReplyDelete