我正在努力弄清楚如何执行以下操作:
我有几种方法可以返回不同的强类型 IEnumerable 对象。这些强类型类共享一个公共基类,该基类公开了我想在 Linq 选择器中访问的属性。
但是我似乎无法让这个工作。如果我只是在方法中传递基类型,那么在绑定 IEnumerable 时会出现错误,因为派生类中可用的属性不可用。
如果我尝试传递类型,那么因为 Linq 表达式不知道类型,所以我无法访问我在 Linq 表达式中需要的属性。
我需要以某种方式告诉 Linq 表达式,我的 IEnumerable 类型是从我的基类派生的。下面是我正在尝试做的一个例子:
private IEnumerable<MyStronglyTypedResultSet> GetReportDetails()
{
// this returns the IEnumerable of the derived type
}
public class MyBaseClass
{
public Guid UserId {get; set;}
public string OfficeName {get; set;}
}
public class MyStronglyTypedResultSet : MyBaseClass
{
public string FullName {get; set;}
public int Age {get; set;}
}
public void MyProblemMethod<T>(IEnumerable<T> allData, string officeToFind)
{
// How do I tell Linq that my <T> type is derived from 'MyBaseClass' so I can access the 'OfficeName' property?
IEnumerable<T> myData = allData.Where(c => c.OfficeName .ToLower().Equals(officeToFind.ToLower()));
MyUsefulObject.DataSource= myData; // This needs to have access to the properties in 'MyStronglyTypedResultSet'
MyUsefulObject.DataaBind();
}