是的,所以我有一个可枚举的,并希望从中获得不同的值.
使用System.Linq,当然有一个名为的扩展方法Distinct.在简单的情况下,它可以在没有参数的情况下使用,例如:
var distinctValues = myStringList.Distinct();
Run Code Online (Sandbox Code Playgroud)
好的,但如果我有一个可以指定相等性的可枚举对象,唯一可用的重载是:
var distinctValues = myCustomerList.Distinct(someEqualityComparer);
Run Code Online (Sandbox Code Playgroud)
equality comparer参数必须是.的实例IEqualityComparer<T>.当然,我可以做到这一点,但它有点冗长,而且很有说服力.
我所期望的是一个需要lambda的重载,比如Func <T,T,bool>:
var distinctValues
= myCustomerList.Distinct((c1, c2) => c1.CustomerId == c2.CustomerId);
Run Code Online (Sandbox Code Playgroud)
任何人都知道是否存在某些此类扩展或某些等效的解决方法?或者我错过了什么?
或者,有没有一种方法可以指定IEqualityComparer内联(embarass me)?
更新
我找到了Anders Hejlsberg对MSDN论坛中关于这个主题的帖子的回复.他说:
您将遇到的问题是,当两个对象比较相等时,它们必须具有相同的GetHashCode返回值(否则Distinct内部使用的哈希表将无法正常运行).我们使用IEqualityComparer,因为它将Equals和GetHashCode的兼容实现打包到一个接口中.
我认为那是有道理的..
我在下面的查询中收到此错误
无法创建类型的常量值
API.Models.PersonProtocol.在此上下文中仅支持基元类型或枚举类型
ppCombined下面是一个IEnumerable对象PersonProtocolType,由2个PersonProtocol列表的concat构成.
为什么这会失败?我们不能使用LINQ JOIN条款里面SELECT的JOIN?
var persons = db.Favorites
.Where(x => x.userId == userId)
.Join(db.Person, x => x.personId, y => y.personId, (x, y) =>
new PersonDTO
{
personId = y.personId,
addressId = y.addressId,
favoriteId = x.favoriteId,
personProtocol = (ICollection<PersonProtocol>) ppCombined
.Where(a => a.personId == x.personId)
.Select( b => new PersonProtocol()
{
personProtocolId = b.personProtocolId,
activateDt = b.activateDt,
personId = b.personId
})
});
Run Code Online (Sandbox Code Playgroud) 两个简单的查询 - 例外情况发生在:
matchings.Any(u => product.ProductId == u.ProductId)
Run Code Online (Sandbox Code Playgroud)
怎么了?如果我写作true而不是一切都很好.
var matchings = (from match in db.matchings
where match.StoreId == StoreId
select match).ToList();
var names = (from product in db.Products
where matchings.Any(u => product.ProductId == u.ProductId)
select product).ToList();
Run Code Online (Sandbox Code Playgroud) Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate);
Run Code Online (Sandbox Code Playgroud)
我将参数传递给Where方法,如下所示:f => f.Id > 4.我可以传递委托方法而不是f.Id > 4吗?
在下面的代码中我得到一个例外
var ret = db.Especialidades.Except(sol.EspecialidadesExigidas).ToList();
Run Code Online (Sandbox Code Playgroud)
这是例外
Unable to create a constant value of type 'TCC.Models.Especialidade'.
Only primitive types or enumeration types are supported in this context.
Run Code Online (Sandbox Code Playgroud)
我已经研究了其他类似的问题,并试图调整他们的答案,但没有成功.其他尝试:
var ret = (from e in db.Especialidades where !sol.EspecialidadesExigidas.Any(e2 => e2.Id == e.Id) select e).ToList();
var ret = (from e in db.Especialidades where !sol.EspecialidadesExigidas.Select(e2 => e2.Id).Contains(e.Id) select e).ToList();
Run Code Online (Sandbox Code Playgroud)
我想要做的是从列表中未包含的数据库中获取所有"Especialidades"