Click here to Skip to main content
15,895,283 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi All,
I want to find a single row from datatable.
I have more then 1 row with same id in data table. I want to find single data-row. If row find with the id then select the row and break. How can i achieve it using LINQ?
Posted
Updated 27-Sep-18 1:28am

C#
int id = 2;
       var item = lstData.FirstOrDefault(k => k.ID == id);
      if (item != null)
      {
// use the Item object to read the properties.
          // your code here...
      }


It always better to use FirstOrDefault instead of single, if you going to search primary key value then we can use singleordefault
if we are in doubt that duplicate records may contains, then we can go for FirstOrDefault.


C#
DataRow drr = dt.AsEnumerable().Where(dr => dr["P"] == id).First();
       var index = dt.Rows.IndexOf(drr);
 
Share this answer
 
v2
Comments
amit_83 3-Jan-14 1:17am    
Thanks, I want to get the display index of row in datatable.
Karthik_Mahalingam 3-Jan-14 1:27am    
can u provide more info?
amit_83 3-Jan-14 1:32am    
DataRow drr = dt.AsEnumerable().Where(dr => dr.Field<guid>("P") == id)
.Select(dr => dr).First();

Instead of getting the row i want to know the index of row. Is it possible to get the row index in the table directly from LINQ?
Karthik_Mahalingam 3-Jan-14 1:48am    
check my updated solution..
amit_83 3-Jan-14 1:57am    
I know this already, its 2 step process, Does it impact the performance?
rest
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900