linq as dataset issue with column names

824 Views Asked by At

How can I avoid using magic strings in a LINQ query against a datatable?

This works:

public IEnumerable getDisplayNames()
{
    IEnumerable nameQry =
        from row in displayTable.AsEnumerable()
        select row.Field("display");

    return nameQry;
}

but this fails with "Specified cast is not valid.":

public IEnumerable getDisplayNames()
{
    string disp = myDictionary["D"];

    IEnumerable nameQry =
        from row in displayTable.AsEnumerable()
        select row.Field(disp);

    return nameQry;
}

My preference is to use a local string (or a direct reference off of myDictionary) instead of hard coding the strings in place. So I want to use the string disp instead of the phrase "display" in my query.

1

There are 1 best solutions below

0
On

Try using

static IEnumerable<DataRow> GetTheRows(DataTable dt, string name)
{
    return dt.AsEnumerable().Where(r => r.Field<string>("yourColumn") == name);
}

or whatever the correct data type is in your given scenario. You need to specify the type when using the Field<T> method.