Reputation: 7705
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.
Upvotes: 0
Views: 5165
Reputation: 34240
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;
Upvotes: 1
Reputation: 83356
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);
Upvotes: 1