[英]Return List based on generic T
I want to convert list of TEntity
to list of TDto
.我想将TEntity
列表转换为TDto
列表。
private List<TDto> ConvertUEntityToDto<TDto, TEntity>(IEnumerable<TEntity> entities)
{
if (entities is IEnumerable<Entity1>)
{
var result = new List<EntityDto1>
foreach (var entity in entities)
{
result.Add(_mapper.Map<EntityDto1>(entity ));
}
return result;
}
else if (entities is IEnumerable<Entity2>)
{
var result = new List<EntityDto2>
foreach (var entity in entities)
{
result.Add(_mapper.Map<EntityDto2>(entity));
}
return result;
}
return null;
}
From code above i get an error:从上面的代码我得到一个错误:
Error CS0029 Cannot implicitly convert type 'System.Collections.Generic.List< EntityDto>' to 'System.Collections.Generic.List< TDto>'错误 CS0029 无法将类型“System.Collections.Generic.List<EntityDto>”隐式转换为“System.Collections.Generic.List<TDto>”
How to return dynamically List of T
from generic method in C#?如何从 C# 中的泛型方法动态返回T
列表?
The meaning of generics are to use them!泛型的意义在于使用它们! The if-else should precede your generic function (also see edit below). if-else 应该在您的通用函数之前(另请参阅下面的编辑)。
if (entities is IEnumerable<Entity1>)
ConvertUEntityToDto<TDto1, Entity1>(entities);
else if (entities is IEnumerable<Entity2>)
ConvertUEntityToDto<TDto2, Entity2>(entities);
else ; //do nothing
and inside ConvertUEntityToDto it should use the T (TDto) as follows:在ConvertUEntityToDto 中,它应该使用 T (TDto),如下所示:
private List<TDto> ConvertUEntityToDto<TDto, TEntity>(IEnumerable<TEntity> entities)
{
var result = new List<TDto>
foreach (var entity in entities)
{
result.Add(_mapper.Map<TDto>(entity));
}
return result;
}
The error was because the return type didn't match with the signature of your function.错误是因为返回类型与您的函数签名不匹配。
You could just pass in a list, iterate it with foreach
and if the element within the list is of type T, then Add to your new List<T>
which you return.您可以只传入一个列表,使用foreach
进行迭代,如果列表中的元素是 T 类型,则添加到您返回的新List<T>
中。
Also, you should have constraints for T.此外,您应该对 T 有约束。
What I mentioned above, to return all element of the list, only which matches the type TDto (and to get rid of the preceding if-else block), we can use the following snippet (by referencing System.Linq
in the project) (thanks @Janne Matikainen to mention):我上面提到的,要返回列表中的所有元素,仅匹配类型 TDto(并摆脱前面的 if-else 块),我们可以使用以下代码段(通过引用项目中的System.Linq
)(感谢@Janne Matikainen 提及):
private List<TDto> ConvertUEntityToDto<TDto, TEntity, Tmixed>(IEnumerable<Tmixed> entities)
{
return entities.Where(e => e is TEntity).Select(e => _mapper.Map<TDto>(e));
}
Which is equivalent to:这相当于:
private List<TDto> ConvertUEntityToDto<TDto, TEntity, Tmixed>(IEnumerable<Tmixed> entities)
=> entities.Where(e => e is TEntity).Select(e => _mapper.Map<TDto>(e));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.