Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I am trying to get value from specific row range.

What I have tried:

This is the code i tried but not sure where should i use the variable rows.

var rows = dt.AsEnumerable().Skip(0).Take(15);
string value = "CB123";
DataRow[] result = dt.Select("BOOKCODE like '%" + value + "%'");
//foreach (var col in rows)
//{  
    if (result.Count() > 0)
     {
       MessageBox.Show("BookCode Not Found");
       //Application.Exit();
     }
//} 
Posted
Updated 6-May-19 20:10pm

You can try something like below. But be aware that the outcome could be different depending on the way the data being sorted in the datatable. Or you can make the datasource to return row_number as suggested by other member and then filter by that variable.


C#
void Test()
{
    DataTable table = new DataTable();
    table.Columns.Add("Dosage", typeof(int));
    table.Columns.Add("Drug", typeof(string));
    table.Columns.Add("Patient", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    // Here we add five DataRows.
    table.Rows.Add(25, "Indocin", "David", DateTime.Now);
    table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);

    table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
    table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
    table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
    table.Rows.Add(22, "xx", "dd", DateTime.Now);

    table.Rows.Add(777, "Dilantin 2", "cc", DateTime.Now);

    //this should return 10,21,100,22
    var resultRange = table.AsEnumerable()
                      .Where((row, index) => index >= 2 && 5 >= index)
                      .CopyToDataTable();

    //this should return 100
    var value = "di";
    var result = resultRange.Select("Drug like '%" + value + "%'");
}




c# - How to select rows from DataTable based on Index / Row Number? - Stack Overflow[^]

https://www.dotnetperls.com/datatable[^]
 
Share this answer
 
You're on the right track...

C#
string bcode = "CB123";
var result = dt.AsEnumerable().Skip(0).Take(15)
     .Where(r=> r.Fields<string>("BOOKCODE").Contains(bcode))
     .ToList();
foreach(var r in result)
{
    //your logic
}


For further details, please see:
LINQ to DataSet | Microsoft Docs[^]
Programming Guide (LINQ to DataSet) | Microsoft Docs[^]
LINQ to DataSet Overview | Microsoft Docs[^]
 
Share this answer
 
rows.Select....

Or you can use
ROW_NUMBER
inside a stored proc to write SQL that filters the data for you.

I have never seen SQL in the filtering of an IEnumerable. I'm not sure this is a good idea.
 
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