Linq: from a List of Type T, Retrieve Only Objects of a Certain Subclass S

LINQ: From a list of type T, retrieve only objects of a certain subclass S

you can do this:

IList<Person> persons = new List<Person>();

public IList<T> GetPersons<T>() where T : Person
{
return persons.OfType<T>().ToList();
}

IList<Student> students = GetPersons<Student>();
IList<Teacher> teacher = GetPersons<Teacher>();

EDIT: added the where constraint.

LINQ - Getting a subset based on type

You can use Enumerable.OfType<T>:

var dogs = animals.OfType<Dog>().ToList();

(Note that the ToList() is only required to make a List<Dog>. If you just need IEnumerable<Dog>, you can leave it off.)

Linq find all with certain type

Use OfType<T> like so:

foreach (var bar in MyList.OfType<Foo>()) {
...
}

How to retrieve an object of a specific subclass?

e.Components.OfType<theType>();

Select only subclasses from collection with Linq

Use OfType<T>:

var onlyChildren = acol.OfType<B>();

LINQ Select projection and different subtypes

I will mark this as answered - came up with a solution although it doesn't exactly fully answer my question. I specifically wanted to know if there was a way to achieve this right inside the LINQ .Select and object initialization.

But I succeeded in cleaning up the duplication using a combination of Nafis Islam's answer to move the object initialization and assignment into a helper function and then by creating each object in the list using it's Type and the Activator class.

Here is what I came up with:

private IEnumerable<BaseClass> GetSubTypeList(IEnumerable<AnotherClass> sourceList, bool myCondition)
{
return sourceList.Select(sl =>
GetSubType(myCondition, sl.Field1, sl.Field2)).ToList();
}

private BaseClass GetSubType(bool myCondition, string field1, string field2)
{
var type = myCondition ? typeof(SubType1) : typeof(SubType2);
var item = (BaseClass) Activator.CreateInstance(type);
item.Field1 = "Field 1";
item.Field2 = "Field 2";
return item;
}

The returned list will now be the type of the correct subclass, and the object initialization is not duplicated.

ListBase contains different Derived types. How to convert safely with LINQ?

You could you use

dList.Where(i=> i is Derived).ToList().ConvertAll(i => (Derived)i);

or

dList.OfType<Derived>().ToList()


Related Topics



Leave a reply



Submit