简体   繁体   English

如何从基于IEqualityComparer的列表中获取对象<T>

[英]How to get an object from a list based upon IEqualityComparer<T>

The Compare method in Linq lets you find by an IEqualityComparer, but I can't find a counterpart method that allows you retrieve an item by the same comparer. Linq中的Compare方法允许您通过IEqualityComparer查找,但我找不到允许您通过同一个比较器检索项目的对应方法。

Is this really the best way to do it? 这真的是最好的方法吗?

MyItem myFinderItem = new MyItem(keyField1, keyField2);
if (myList.Contains(myFinderItem, new MyEqualityComparer()))
{
    MyItem myRealItem = myList.Single(item => new MyEqualityComparer().Equals(item , myFinderItem));
}

(I'm sharing the usage of the IEqualityComaprer with a call to the Except Linq method and I'd like to maintain a single source for equality comparisons) (我正在通过调用Except Linq方法分享IEqualityComaprer的用法,我想维护一个单一来源进行相等比较)

Edit: What I'm looking for a method that has the signature: 编辑:我正在寻找具有签名的方法:

T Find<T>(T t, IEqualityComparer<T> comparer)

Edit2: I guess this works, it's funky . 编辑2:我想这很有效, 它很时髦 but it's horrible and would never use it :( 但它太可怕了,永远不会用它 :(

myList.Intersect( new List<MyItem>{myFinderItem}, comparer).Single();

First, you should use the same instance of MyEqualityComparer rather than creating a new instance every time (you should perhaps consider making it a singleton). 首先,您应该使用相同的MyEqualityComparer实例,而不是每次都创建一个新实例(您应该考虑将其设置为单例)。

Other than that, I don't think there's a much better way of doing it. 除此之外,我认为没有更好的方法。 If you want to make it shorter and more readable, you could create an extension method that takes a IEquaityComparer<T> instead of a predicate : 如果你想让它更短更易读,你可以创建一个扩展方法,它接受IEquaityComparer<T>而不是谓词:

public static T Single<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer, T value)
{
    return source.Single(item => comparer.Equals(item, value));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM