在Linq语句中使用"匹配"

Ret*_*der 7 c# regex linq-to-entities

我有一个有两个记录的表(运行时会有很多).该deviceId的记录,"DEVICE1"和"DEVICE2".我想使用正则表达式来提取记录.

下面的代码编译但无法返回结果.当我将光标悬停在"devices.ToList()"语句上时,我收到以下错误:

base {System.SystemException} = {"LINQ to Entities does not recognize the method 'System.Text.RegularExpressions.MatchCollection Matches(System.String)' method, and this method cannot be translated into a store expression."}”

任何人都可以告诉我如何修改我的查询,以便这将返回基于表达式的记录?

filterText = @"DEVICE.";
Regex searchTerm = new Regex(filterText);

using (var ctx = new MyEntities())
{
 var devices = from d in ctx.Devices
                let matches = searchTerm.Matches(d.DeviceId)
                where matches.Count > 0
                select ((Device)d);
return devices.ToList();
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 17

我不相信你可以使用LINQ to Entities的正则表达式.但是,看起来您只是想找到以"DEVICE"开头的设备,因此查询将是:

return ctx.Devices.Where(d => d.DeviceId.StartsWith("DEVICE"))
                  .ToList();
Run Code Online (Sandbox Code Playgroud)

编辑:如果您确实需要正则表达式的灵活性,您应该首先将设备ID(以及设备ID)提取回客户端,然后对其执行正则表达式,最后获取其余数据,匹配这些查询:

Regex regex = new Regex(...);

var deviceIds = ctx.Devices.Select(d => DeviceId).AsEnumerable();

var matchingIds = deviceIds.Where(id => regex.IsMatch(id))
                           .ToList();

var devices = ctx.Devices.Where(d => matchingIds.Contains(d.DeviceId));
Run Code Online (Sandbox Code Playgroud)

这是假设获取所有设备的所有数据实际上是昂贵的.如果这不是太糟糕,那将是一个更简单的选择.要强制在进程中执行处理,请使用AsEnumerable():

var devices = ctx.Devices.AsEnumerable()
                         .Where(d => regex.IsMatch(d.DeviceId))
                         .ToList();
Run Code Online (Sandbox Code Playgroud)

  • @Retrocoder:如果你需要更多的灵活性,你应该在问题中这么说. (3认同)