C#动态Linq:假定字符串为整数?

时间:2019-01-16 21:09:21

标签: c# mysql sql linq

我正在使用此处找到的System.Linq.Dynamic库,它只是Microsoft库的上载,可以通过NuGet访问:https://github.com/kahanu/System.Linq.Dynamic

在我的代码中,我具有此函数,该函数从数据库中获取与某个属性匹配的对象列表。它需要尽可能灵活,因此参数由三个字符串组成;

  • 一个用于“ order by”语句的
  • 一个与属性名称匹配的属性
  • 一个代表期望属性的值

这是给我麻烦的代码行:

public IQueryable<T> GetByProperty(string propertyName, string propertyValue,
    string orderStatement)
{
    return _context.Set<T>()
        .OrderBy(orderStatement)
        .Where(propertyName + " = " + propertyValue);
}

这里是可能的情况;

  • propertyValue仅包含数字:查询工作正常。
  • propertyValue以数字开头,但其中包含字母:出现以下错误:Operator '=' incompatible with operand types 'String' and 'Int32'

  • propertyValue是其他值:出现以下错误:No property or field '[the first part of the "propertyValue string, up until it meets an empty space, a "-" or some other specific characters]' exists in type '[Class name of <T>]'

我尝试使用单引号将我的字符串括起来,但是随后出现错误:'Character literal must contain exactly one character'

我也拼命尝试在末尾添加“ .ToString()”,以尝试使某些东西起作用,但是我发现了错误:Digit expected

在Linq和Dynamic Linq中,还有另一种使用“ Where”子句的方式可以支持我尝试使用此结构的灵活性吗?

1 个答案:

答案 0 :(得分:1)

您需要知道属性的类型并相应地设置值的格式。如果是字符串,请用双引号将其引起来。即nm1 = names(df1) nm2 = names(df2) nm = intersect(nm1, nm2) if (length(nm) == 0){ # if no column names in common cbind(df1, df2) } else { # if column names in common cbind(df1[!nm1 %in% nm2], # columns only in df1 df1[nm] + df2[nm], # add columns common to both df2[!nm2 %in% nm1]) # columns only in df2 } # D A C B #1 1 2 2 1 #2 2 4 4 2 name = "John"

不取决于该值是否看起来像数字。

  • 如果属性的类型是数字类型,则该值也必须是数字,并且不能用引号引起来。
  • 如果属性的类型为字符串,则该值必须用双引号引起来,即使该值是一个数字(例如age = 20)。