Linq select 行,其中列第 n 个字符 = x

Linq select row where columns nth character = x

我有一个遗留数据库,我需要在其中获取特定类型的所有行。没有用于搜索该类型的列,但幸运的是,当它是我想要的类型时,有一个命名约定,每个第 3 个字符都有破折号。我以为我可以简单地这样做:

var sectionsList = (from sec in db.Query<Section>()
                                     where (sec.Name[2] == '-')
                                     select sec).ToList().Distinct();

但是我得到这个错误:

An exception of type 'System.NotSupportedException' occurred in NHibernate.dll but was not handled in user code Additional information: Char get_Chars(Int32)

我发现这看起来是同一个问题: LINQ to Entities does not recognize the method Int32 get_Item(Int32) 但这种情况涉及与可以事先获取的本地值进行比较。我需要在搜索过程中遍历名称字符串。

我们应该使用Substring方法:

var sectionsList = 
  (
    from sec in db.Query<Section>()
    where sec.Name.Substring(2,1) == "-")
    select sec
  )
  .ToList().Distinct();

并且应该将其转换为 DB 函数,例如:substring(NAME, 2, 1) = '-'