c# - 使用 Linq 和继承绑定(bind)到对象的通用方法

标签 c# linq c#-4.0

我正在努力思考如何执行以下操作:

我有几种返回不同强类型 IEnumerable 对象的方法。 这些强类型类共享一个公共(public)基类,该基类公开我想要在 Linq 选择器中访问的属性。

但是我似乎无法让它工作。如果我只是在方法中传递基类型,那么在绑定(bind) 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();
}

最佳答案

您可以使用OfType扩展方法。

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.OfType<MyBaseClass>.Where(c => c.OfficeName .ToLower().Equals(officeToFind.ToLower()));
    MyUsefulObject.DataSource= myData;
    MyUsefulObject.DataaBind();
}

关于c# - 使用 Linq 和继承绑定(bind)到对象的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11187537/

相关文章:

c# - 如何在 ConfigureServices .Net Core 3.1 中注册具有多个接口(interface)的服务并将该服务用作单个实例

.net - 2个不同类型列表的平等

c# - LINQ 方法的序列有什么重要性吗?

c# - 按 unicode 类别拆分字符串

asp.net - 如何在Azure中的Documentdb中编写和编译存储过程

c# - 使用 ASP.NET 和 C# 将 csv 文件导入 SQL Server

c# - PartialView Action 正在调用自身

c# - 为什么要使用序列化

c# - 如何在没有提示的情况下使用ADAL,NetStandard和Azure AD对CRM Dynamics Online Web服务进行身份验证

c# - 如何将带有 group by 子句的 SQL select Count 转换为 LINQ?