I have an abstract class called Grouping. I have a subclass called GroupingNNA.
public class GroupingNNA : Grouping {
// blah blah blah
}
I have a List that contains items of type GroupingNNA, but is actually declared to contain items of type Grouping.
List<Grouping> lstGroupings = new List<Grouping>();
lstGroupings.Add(
new GroupingNNA { fName = "Joe" });
lstGroupings.Add(
new GroupingNNA { fName = "Jane" });
The Problem: The following LINQ query blows up on me because of the fact that lstGroupings is declared as List< Grouping> and fName is a property of GroupingNNA, not Grouping.
var results = from g in lstGroupings
where r.fName == "Jane"
select r;
Oh, and this is a compiler error, not a runtime error. Thanks in advance for any help on this one!
More Info: Here is the actual method that won't compile. The OfType() fixed the LINQ query, but the compiler doesn't like the fact that I'm trying to return the anonymous type as a List< Grouping>.
private List<Grouping> ApplyFilterSens(List<Grouping> lstGroupings, string fSens) {
// This works now! Thanks @Lasse
var filtered = from r in lstGroupings.OfType<GroupingNNA>()
where r.QASensitivity == fSens
select r;
if (filtered != null) {
**// Compiler doesn't like this now**
return filtered.ToList<Grouping>();
}
else
return new List<Grouping>();
}