views:

241

answers:

1

Hi, I'm still learning (baby steps). Messing about with a function and hoping to find a tidier way to deal with my datatables.

For the more commonly used tables throughout the life of the program, I'll dump them to datatables and query those instead. What I'm hoping to do is query the datatables for say column x = "this", and convert the values of column "y" directly to a List to return to the caller:

    private List<string> LookupColumnY(string hex)
    {
        List<string> stringlist = new List<string>();
        DataRow[] rows = tblDataTable.Select("Columnx = '" + hex + "'", "Columny ASC");
        foreach (DataRow row in rows) { stringlist.Add(row["Columny"].ToString()); } 
        return stringlist;
    }

Anyone know a slightly simpler method? I guess this is easy enough, but I'm wondering if I do enough of these if iterating via foreach loop won't be a performance hit. TIA!

+3  A: 

You can use LINQ to simplify this:

public IEnumerable<string> LookupColumnY(string hex)
{
     return tblDataTable
                .Select("Columnx = '" + hex + "'", "Columny ASC")
                .Select(row => row["Columny"].ToString() );
}

If you need to return a list, you can add ToList():

public IList<string> LookupColumnY(string hex)
{
     return tblDataTable
                .Select("Columnx = '" + hex + "'", "Columny ASC")
                .Select(row => row["Columny"].ToString() )
                .ToList();
}

However, this will still iterate each row in the selection.

Reed Copsey
Okay thanks! Much appreciated!
James