IEnumerable<T> 使用 c# 在函数内访问 T 的属性

问题描述

一个 c# 函数接受一个列表作为 IEnumerable<T>。我想在这函数中写一些 linq 查询,但是 T属性似乎没有得到。

在编写 Linq 语句之前,我们如何将 T 映射到特定类型?在本例中,它的类型为 CustomerAddress,具有 3 个属性 Id,Name,Gender

private IEnumerable<IEnumerable<T>> SmartSplit<T>(IEnumerable<T> sourceList)
{
    // not able to access any props of T; in this case T is of type CustomerAddress
    int itemsCount = sourceList.Where(v => v.???==).Count();  
}
    

我想在此函数获取 itemsCount 作为名称长度 > 50 的项目数。 Linq 将针对一个列表就像

int itemsCount = sourceList.Where(p => p.Name.Length > 50).Count();
        

但是如何访问 Name 函数内的属性 SmartSplit?我可以看到有一种方法可以通过先转换为列表然后像下面这样编写 LINQ

private IEnumerable<IEnumerable<T>> SmartSplit<T>(IEnumerable<T> sourceList)
{
    List<CustomerAddress> sourceListcopy = sourceList as  List<CustomerAddress>;
    int itemsCount=  sourceListcopy.Where(p => p.Name.Length > 50).Count();
}

我们可以在不强制转换和复制到函数内的临时列表的情况下执行此操作吗?

解决方法

如果您不仅要传递 CustomerAddress,还应该将公共属性提取到接口,然后使用带有“where”子句的约束。
示例:

  public interface ICustomerInfo
    {
        string Name { get; set; }
    }

    private IEnumerable<IEnumerable<T>> SmartSplit<T>(IEnumerable<T> sourceList) where T: ICustomerInfo,class
    {
        int itemsCount = sourceList.Where(v => v.Name.Length > 50).Count();
        return default;
    }