views:

27

answers:

1

I am putting information from a folder into a datatable. I'm putting the info into the datatable using the following code line:

dtUpgradeFileInfo.Rows.Add(nums[0],nums[1],nums[2],test1);

It appears to be working but I'm not as familiar with datatables in C# as I am in VB. How would i search the datatable where the first column has a certain value and the third column has the highest value in case there are multiple rows with the same value in the first column. I am also unsure of how to retrieve the info once I've found the row I need. The type for each column is int,int,int,string respectively.

A: 

If by VB you mean VB.NET and not something like VB6, then the code to work with DataTables (as opposed to legacy VB recordsets) will be the same in C#. Rather, the methods you would employ, obviously the syntax will be differently because it's C#. There's semi-colons and brackets where you might except parentheses. But they're using the same objects, calling the same methods.

Anyway, you could do this (C# 3.0+)

DataRow matchingRow = (from DataRow row in dtUpgradeFileInfo.Rows
                       where (int)row["Column1"] == yourValue
                       orderby (int)row["Column3"] descending
                       select row).FirstOrDefault();

if (matchingRow != null)
{
    // get to work
}

And for a non-LINQ answer (any version of C#)

string filter = "Column1 = " + yourValue.ToString();
string sortOrder = "Column3 desc";

dtUpgradeFileInfo.DefaultView.RowFilter = filter;
dtUpgradeFileInfo.DefaultView.Sort = sortOrder;
DataRow myRow = null;
DataTable filteredTable = dtUpgradeFileInfo.DefaultView.ToTable();
if (filteredTable.Rows.Count > 0)
    myRow = filteredTable.Rows[0];

if (myRow != null)
{
    // get to work
}
Anthony Pegram
Maybe I'm doing something wrong but I can't get this to work. Error lines everywhere asking for semicolons in the middle of the lines and invalid ) and invalid in.
Bryan
And VB.Net 2008 is what i'm used to using.
Bryan
Sorry, typo, wasn't typing in an IDE. If you have more issues, this expects that you have `using System.Data;` and `using System.Linq;` in your file.
Anthony Pegram
@Bryan, did not notice your C# 2.0 tag earlier. I have added code that should work in that environment.
Anthony Pegram