从 DataTable 中选择前 1 个,其中列顺序按 Column 作为字符串

Ash*_*Ash 2 c# datatable

查看我需要解析的示例结果图片

请参阅上面的C#数据表的值。我需要根据 colA 和 dateof获取突出显示的值,我可以用 SQL 对其进行解释,如下所示:

SELECT TOP 1 colB FROM dt WHERE colA = 'aaa' ORDER BY dateof ASC
Run Code Online (Sandbox Code Playgroud)

我必须用C#来做,而不是用 SQL。

我怎样才能得到这个值?

suj*_*lil 5

您可以尝试以下代码并让我知道它是否有帮助吗?令myDataTable为您正在处理的数据表,假设字段的类型为string(如果需要,请适当更改)

myDataTable.AsEnumerable()
           .Where(x => x.Field<string>("colA") == "aaa")
           .OrderBy(y => y.Field<string>("dateof"))
           .Take(1)
           .Select(s => s.Field<string>("colB"))
Run Code Online (Sandbox Code Playgroud)

否则这可能会帮助你:

var defaultSelectedRow = myDataTable.AsEnumerable()
                                    .Where(x => x.Field<string>("colA") == "aaa")
                                    .OrderBy(y => y.Field<string>("dateof")).FirstOrDefault();
if (defaultSelectedRow != null)
{
    string colBValue = defaultSelectedRow.Field<string>("colB");
}
Run Code Online (Sandbox Code Playgroud)