Reputation: 2070
I'm trying to remove several items from a List which match a specific condition before I add the contents to a ListBox. I want anything which is (enum) "MediaState.Deleted" removing from the list.
So far I have tried:
//does not remove anything
dbAssetList.RemoveAll(x => x.MediaState.Equals(6));
//Error on .equals which states that "Cannot access static method equals in non-static context"
dbAssetList.RemoveAll(x => x.MediaState.Equals(typeof(MediaState),MediaState.Deleted));
//Error on .equals which states that "Cannot access static method equals in non-static context"
dbAssetList.RemoveAll(x => dbAssetList.Contains(x.MediaState.Equals(typeof(MediaState), MediaState.Deleted)));
What am I doing wrong, how can remove items in my list which are "MediaState.Deleted"
Upvotes: 0
Views: 266
Reputation: 20722
The first variant of your code does not remove anything because Equals
will always return false
:
According to the docs of that method, the return value is:
true
ifobj
is an enumeration value of the same type and with the same underlying value as this instance; otherwise,false
.
If you pass the literal 6
to Equals
, the conditions for true
are not fulfilled, als 6
is of type int
, not of type MediaState
.
The other two variants are resolved by the compiler to the static Equals
method provided by System.Object
(as it is the nearest Equals
method with two parameters). The compiler will not compile that as you do not call that static method on System.Object
, but on a reference typed to one of the subclasses thereof. As static methods are not resolved based on the current type pointed to by a variable, but at compile-time, such a call will not compile.
Instead, just use
listBox.Items.Add(dbAssetList.Where(x => x.MediaState != MediaState.Deleted));
The ==
operator for comparisons works well with enum values in C#.
Upvotes: 3
Reputation: 1269
dbAssetList.RemoveAll(x => x.MediaState.Equals(MediaState.Deleted));
or
dbAssetList.RemoveAll(x => x.MediaState == MediaState.Deleted);
.Equals(6) won't match any items in the list. The typeof() versions of Equals are static and can't be used in that context.
Upvotes: 0