C# IEnumerable<;T>;使用c访问函数中T的属性#

C# IEnumerable<;T>;使用c访问函数中T的属性#,c#,linq,ienumerable,C#,Linq,Ienumerable,有一个c#函数,它将列表接受为IEnumerable。我想在这个函数中编写一些linq查询,但是T的属性似乎没有得到满足 在编写Linq语句之前,如何将T映射到特定类型?在本例中,它的类型为CustomerAddress,具有3个属性Id、Name、Gender private IEnumerable<IEnumerable<T>> SmartSplit<T>(IEnumerable<T> sourceList) { // not able

有一个c#函数,它将列表接受为
IEnumerable
。我想在这个函数中编写一些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();  
}
    
但是如何访问
SmartSplit
函数中的属性
Name
?我可以看到,有一种方法可以做到这一点,即先对列表进行强制转换,然后像下面这样编写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();
}
private IEnumerable智能拆分(IEnumerable源列表)
{
List sourceListCopy=源列表为列表;
int itemscont=sourceListCopy.Where(p=>p.Name.Length>50.Count();
}

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

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

公共接口ICCustomerInfo
{
字符串名称{get;set;}
}
私有IEnumerable SmartSplit(IEnumerable sourceList),其中T:ICCustomerInfo,类
{
int itemscont=sourceList.Where(v=>v.Name.Length>50).Count();
返回默认值;
}

那么就不要让
SmartSplit
接受
IEnumerable
!使其接受
IEnumerable
。似乎您的函数导出的是
IEnumerable
,而不是
IEnumerable
,除非
T
被约束为
CustomerAddress
。如果您不想将其约束为
CustomerAddress
,您可以使用声明
字符串名称
属性的接口,并使
CustomerAddress
实现该接口。对于您当前的代码,无法保证任何类型
T
在旁注
中都有
名称
属性,其中(p=>…).Count()可以重写
.Count(p=>…)
,如果您不想指定类型或接口而不是泛型,然后您也可以将
Where
子句作为参数传递。为什么建议使用约束而不是
IEnumerable
?因此,在您的情况下,方法始终应该返回接口。若你们不需要那个样做,你们可以在通过内部时使用约束返回精确的类型。例如:
IEnumerable split=SmartSplit(new List())

IEnumerable split1=SmartSplit(新列表())带有接口:
IEnumerable split=SmartSplit(new List())

IEnumerable split1=SmartSplit(新列表())
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();
}
  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;
    }