查询 DataTable 过滤字段中的第一个字符

Querying a DataTable filtering for first char in field

我是 Linq 的新手,我无法理解这个查询。

我有一个数据表,其中有一个字段“RecordType” 我想使用 RecordType 的首字母过滤某些行字段 过滤器是一个字符串“A,B”,应该只获取 RecordType 以 A 或 B

开头的记录

我的查询是:

string filter = "A,B";
var query = table.AsEnumerable()
                .Where (row => filter.Contains(row.Field<string>("RecordType").Trim().ToUpper().First()))
                .Select(s => s["FieldA"])
                .Distinct()
                .ToList();

我收到“System.Data.DataRowExtensions.Field(...) 返回空值。”

我做错了什么?

以及如何在 Select 中 select 多个字段?

您需要使用 StartsWith()

进行过滤
var query = table.AsEnumerable()
       .Where (row => row.Field<string>("RecordType").StartsWith("A", StringComparison.InvariantCultureIgnoreCase) || row.Field<string>("RecordType").StartsWith("B", StringComparison.InvariantCultureIgnoreCase)))
       .Select(s => s["FieldA"])
       .Distinct()
       .ToList();

如果你想考虑一个过滤器变量,那么你可以将上面的查询与 Any().

结合起来

由于您的 filter 变量由 , 分隔,我使用 .Split(',') 将字符串转换为字符串数组。

string filter = "A,B";
var query = table.AsEnumerable()
       .Where (row => filter.Split(',')
       .Any(x => row.Field<string>("RecordType").StartsWith(x, StringComparison.InvariantCultureIgnoreCase))
       .Select(s => s["FieldA"])
       .Distinct()
       .ToList();

.First() 将 return 第一行,而不是第一个字母。

尝试s.Substring(0, 1) == 'A'检查字符串中的第一个字符是否为A

为了解决您收到的错误,我们需要明确告诉字段调用 return 类型可能为空(又名:string?)。然后,在尝试操作字符串之前,我们需要在字段调用之后检查空值。

string filter = "A,B";
var query = table.AsEnumerable()
    .Where (row => filter.Contains(
        // get a nullable string from Field() and then use the "" value if it is null
        (row.Field<string?>("RecordType") ?? "")
            // pad the string to ensure there is at least one character to get in the substring call
            .PadRight(1)
            // get the first character of the string and upper-case it
            .Substring(0, 1).ToUpper()))
            .Select(s => s["FieldA"])
            .Distinct()
            .ToList();