Linq - 不以前缀范围中的任何前缀开头

时间:2011-07-13 08:06:45

标签: c# linq

我需要创建一个具有以下逻辑的Linq查询:

IEnumerable<string> prefixes = GetListOfPrefixesFromSomewhere();
IQueryable<Record> myQuery = GetAllRecordsFromRepository();
foreach (string prefix in prefixes)
{
  myQuery = myQuery.Where(x => !x.Field.StartsWith(prefix));
}

这显然会导致一个大的IQueryable,然后可以执行。

有一种很好的方式来表达这是一个单一的Linq声明吗?

1 个答案:

答案 0 :(得分:2)

你至少可以尝试

// Only call ToList if you need to, of course... but I think EF/LINQ To SQL
// will need it as a list (or array)
List<string> prefixes = GetListOfPrefixesFromSomewhere().ToList();

IQueryable<Record> query = GetAllRecordsFromRepository()
             .Where(x => !prefixes.Any(prefix => x.Field.StartsWith(prefix)));

SQL会是什么样子,我不知道 - 但我认为逻辑上你想要什么,这通常是一个好的开始。

相关问题