获取列值

时间:2011-06-24 22:41:16

标签: linq-to-dataset

    private string FindTaxItemLocation(string taxItemDescription)
    {
        if (!templateDS.Tables.Contains(cityStateTaxesTable.TableName))
            throw new Exception("The schema dos not include city state employee/employer taxes table");
        var cityStateTaxes =
            templateDS.Tables[cityStateTaxesTable.TableName].AsEnumerable().FirstOrDefault(
                x => x.Field<string>(Fields.Description.Name) == taxItemDescription);//[x.Field<string>(Fields.SteStateCodeKey.Name)]);

        if (cityStateTaxes != null)
            return cityStateTaxes[Fields.SteStateCodeKey.Name].ToString();

        return null;
    }

cityStateTaxes是一个DataRow,为什么/如何在FirstOrDefault()中获取列值?

谢谢,

1 个答案:

答案 0 :(得分:1)

FirstOrDefault()选择集合中的第一个项目(可选地满足谓词)或者在它为空(或者没有任何内容满足谓词)的情况下返回null。它不会为你做预测。因此,如果您使用它,访问项目的字段可能会很麻烦,因为您必须包含默认值检查。

我的建议是在使用FirstOrDefault()之前总是投射到您想要的字段,这样您就可以直接获得字段,而无需执行检查。

var cityStateTaxes = templateDS.Tables[cityStateTaxesTable.TableName]
    .AsEnumerable()
    .Where(row => row.Field<string>(Fields.Description.Name) == taxItemDescription) // filter the rows
    .Select(row => row.Field<string>(Fields.SteStateCodeKey.Name)) // project to your field
    .FirstOrDefault(); // you now have your property (or the default value)

return cityStateTaxes;
相关问题