Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering the object of a type with OfType in C#

Tags:

c#

linq

oftype

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?

like image 345
prosseek Avatar asked Apr 15 '12 20:04

prosseek


People also ask

What is the function Of the OfType()?

OfType() operator is used to return the element of the specific type, and another element will be ignored from the list/collection.

Which operator filter the elements of a sequence based on a type?

OfType operator filters the sequence or data source depends upon their ability to cast an element in a collection to a specified type.

What is OfType C#?

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.

What is filter in C sharp?

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.


1 Answers

There are two problems:

  • OfType returns IEnumerable<T>, not T
  • It's a method - you forgot the brackets

Perhaps you wanted:

Base f = list.OfType<A>().FirstOrDefault();

?

like image 166
Jon Skeet Avatar answered Oct 10 '22 16:10

Jon Skeet