ObservableCollection find item match on reference equality

Its late so this may be a dumb question... If Fish is a class (with no Equal/operator== overrides/overloads) and I want to get a specific fish matched on reference equality from a List or ObservableCollection of Fish(es) currently I do:

Fish found_fish1 = my_list.Find(f => f==search_fish);
Fish found_fish2 = my_observable_collection.FirstOrDefault(f => f==search_fish);

Is that the best way to do this? I was expecting an XXXX method that takes a Fish (similar to Remove) eg

Fish found_fish = my_observable_collection.XXXX(search_fish);

but just can't seem to find it.

Answers


Since found_fish is either search_fish or null, you can use ICollection<T>.Contains:

Fish found_fish1 =
    my_list.Contains(search_fish) ? search_fish : null;
Fish found_fish2 =
    my_observable_collection.Contains(search_fish) ? search_fish : null;

Yes, that is the correct way.

Find takes a Preciate<Fish>, and FirstOrDefault takes a Func<Fish, bool>, so your signature will work for both; both signatures expect a single Fish, and a return value of boolean.

But since you're really just testing to see if a given fish is in your collection, why not just use Any()

bool searchFishExists = my_observable_collection.Any(f => f == search_fish);

Need Your Help

How to tell cucumber go to some page?

ruby-on-rails

I'm learning to test with cucumber + capybara.

Objective-C put string at location of another string

objective-c string nsstring substring

I wan't to "know" how to put a string at a location in another string. I already know because I figured out another way to do this. But I wan't to know the real way, does it even exist?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.