How to fill List <string> with Datarow values ​​from separate columns

I'm still learning (baby steps). Chatting with a function and hoping to find a neater way to deal with my data.

For more frequently used tables, throughout the life of the program, I will dump them to datatables and query them. What I hope to do is query the column data for column x = "this" and convert the values ​​of column "y" directly to a list to get back 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;
    }

      

Does anyone know a slightly simpler method? I think this is easy enough, but I'm wondering if I'll do enough if iterating through the foreach loop isn't a performance hit. TIA!

+2


source to share


1 answer


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 over every line in the list.

+4


source







All Articles