简体   繁体   中英

linq as dataset issue with column names

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM