开发者

Find an item inside a List<T> by providing a sample object instance

Why is there a List<T>.Contains(T) method but no List<T>.Find开发者_运维百科(T) method? Only the Finds that support predicates are supported. If we have an existing instance of T populated with a property value for its ID (but missing other properties) why can't we search by providing this object instance to the search in List, especially when we have implemented custom IEquatable<T> for T and would like to use what's there. But as it is, we can't, we have to repeat everything that we did in IEquatable implementation in our Find(predicate) call.


You can call the IEquatable<T> member(s) in your Predicate<T>. Then you won't be repeating yourself.

MyClass a = new MyClass(); //sample for finding; IEquatable<MyClass>
List<MyClass> list = GetInstances();

MyClass found = list.Find( mc => mc.Equals(a) );


how about this

list.Any(i => i.ID == searchObj.ID);


EDIT:

I think I understood your question now. You can use the List<T>.IndexOf method for this purpose:

int index = myList.IndexOf(mySample);

if(index != -1)
{
   var item = myList[index];
   // Do something with item.
}

But this would be quite strange, because clearly, your equality definition isn't quite the whole picture - it's a bit of an abuse of equality, IMO.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜