我有一个方法,除了一个IEnumerable<T>
和一个lambda表达式,它描述了用来比较一个linq-to-sql集合到一个数组的字段。该方法返回匹配的记录。匿名方法的问题
public IEnumerable<ZipCode> match<T>(IEnumerable<T> values,
Func<ZipCode, T> matchPhrase) {
return (from zipCode in _table
where values.Contains<T>(matchPhrase)
select zipCode).Distinct();
}
,我发现了错误:
Argument type
'Func<ZipCode, T>'
is not assignable to parameter type'T'
的方法将被称为像这样(其中values
是IEnumerable<string>
和x.zipcode
是string
):
var zipCodes = _zipCodeRepository.match(values, x => x.zipcode)
UPDATE
基于使用HashSet<T>
约翰的建议,我已经改变了我的代码,但我得到一个不同的错误,现在
Method 'System.Object DynamicInvoke(System.Object[])' has no supported translation to SQL.
我想我可能不会一直在清楚我的问题,我想我用错了方法签名来获得我想要的结果。让我用一个更简单的代码示例来解释:
public IEnumerable<ZipCode> match(IEnumerable<string> values) {
return (from zipCode in _table
where values.Contains(zipCode.zipcode)
select zipCode).Distinct();
}
我打算完成此操作,但使用匿名类型。我想通过lambda来通过在Contains()
中使用的字段。所以zipCode.zipcode
将被传递到方法的第二个参数:x => x.zipcode
你几乎肯定希望把'values'成'HashSet'在一开始,这样就可以更有效地搜索它。因为它是枚举'values',对'_table'中的每个项目进行线性搜索。这是非常低效的,并且可重复枚举多次,这真的应该在这样的函数中避免。 – Servy