65.9K
CodeProject is changing. Read more.
Home

Generic LINQ Usage To Return Single Value From DataRow

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Jul 15, 2010

CPOL
viewsIcon

26727

This tip will allow you to return the value from column X, where column Y matches your filter

I've used LINQ to objects for ever, but have stayed away from LINQ to sql for a while, because we don't exclusive use SQL Server. I recently began toying with the System.Data.DataSetExtensions, and realized LINQ was a much faster (easier to code anyways) way to get the value from a DataColumn out of a DataTable. Let's say I have a table of persons names, and I want to get the last name where the person_id = 100. I used to do something like this:
var persons = new DataTable();

string lastName = string.Empty;

DataRow[] foundRows = persons.Select("Person_Id = 100");
if (foundRows.Length == 1)
{
    lastName = foundRows[0]["Last_Name"].ToString();
}
now with LINQ, I have created the following method:
        
public static T GetFirstResultValue<t,ty>(DataTable table,string colToSearch, string colToReturn, TY searchValue) where TY: IComparable
{
    T ret = default(T);

    IEnumerable rows = from row in table.AsEnumerable()
                                        where row.Field(colToSearch).CompareTo(searchValue) == 0
                                        select row;

    if (rows.Count() == 1)
    {
        ret = (T) rows.First()[colToReturn];
    }

    return ret;
}
This particular method will only work if the results of the search return 1 row, but it could easily be tweaked to return the DataRow collection, or an IEnumerable list of column values for the found rows. Hope this helps someone!