I have a base class Base, and class A/B that inherits from it.
public class Base
{
int x;
}
public class A : Base
{
int y;
}
public class B : Base
{
int z;
}
I tried to use OfType to filter the only object that I need as follows:
public static void RunSnippet()
{
Base xbase; A a; B b;
IEnumerable<Base> list = new List<Base>() {xbase, a, b};
Base f = list.OfType<A>; // I need to get only the object A
Console.WriteLine(f);
}
When I compiled the code, I got this error:
error CS0428: Cannot convert method group 'OfType' to non-delegate type 'Base'. Did you intend to invoke the method?
What's wrong with the code?
OfType() operator is used to return the element of the specific type, and another element will be ignored from the list/collection.
OfType operator filters the sequence or data source depends upon their ability to cast an element in a collection to a specified type.
C# OfType() MethodFilter a collection on the basis of each of its elements type. Let's say you have the following list with integer and string elements − list. Add("Katie"); list. Add(100); list.
Filtering refers to the operation of restricting the result set to contain only those elements that satisfy a specified condition. It is also known as selection. The following illustration shows the results of filtering a sequence of characters.
There are two problems:
OfType
returns IEnumerable<T>
, not T
Perhaps you wanted:
Base f = list.OfType<A>().FirstOrDefault();
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With