Question

I'm working on a project where I'm converting an old VB6 project to .NET/C#. I've come upon a method that performs several queries, once of which uses the recordset.FindFirst method to generate sub-results. I'm at a loss on how to translate this into C# without using LINQ (something I have no experience with anyway). I've search through Google, etc and cannot find a relevant example that doesn't use LINQ. Can anyone provide me with a simple C# example that executes a query, then executes a sub-clause against those results without using LINQ?

In my code I am using an OldDbConnection and an OleDbReader to query the table from the Access database. Perhaps this is wrong?

Many thanks in advance for any examples you can provide.

Was it helpful?

Solution

One way to do it would be to load the initial query results into a DataTable and then use the .Select method to run the secondary query against the initial results. For example, for a table named [Users] in Access containing...

ID  UserName
--  --------
1   Jeff
2   Greg
3   Garth
4   Gord
5   Gary
6   Grant
7   Graham

...the following C# code...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;

namespace oledbTest1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var conn = new OleDbConnection())
            {
                conn.ConnectionString =
                        @"Provider=Microsoft.ACE.OLEDB.12.0;" +
                        @"Data Source=C:\__tmp\testData.accdb;";
                conn.Open();
                using (var cmd = new OleDbCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText =
                        "SELECT * FROM Users WHERE ID < 7 ORDER BY UserName";
                    var da = new OleDbDataAdapter(cmd);
                    var dt = new System.Data.DataTable();
                    da.Fill(dt);
                    Console.WriteLine("The initial query from the Access database (WHERE ID < 7) returned:");
                    foreach (System.Data.DataRow dr in dt.Rows)
                    {
                        Console.WriteLine(dr["UserName"]);
                    }
                    System.Data.DataRow[] subsetRows;
                    subsetRows = dt.Select("UserName LIKE 'Gr%'");
                    Console.WriteLine();
                    Console.WriteLine("The equivalent of \".FindFirst UserName LIKE 'Gr%'\" on that subset would be:");
                    Console.WriteLine(subsetRows[0]["UserName"]);
                }
                conn.Close();
            }
        }
    }
}

...produces the following result:

The initial query from the Access database (WHERE ID < 7) returned:
Garth
Gary
Gord
Grant
Greg
Jeff

The equivalent of ".FindFirst UserName LIKE 'Gr%'" on that subset would be:
Grant
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top