gpt4 book ai didi

c# - 将 IQueryable 转换为 IQueryable

转载 作者:行者123 更新时间:2023-12-03 15:25:10 25 4
gpt4 key购买 nike

我们正在尝试转换 IQueryable<EntityObject> 的实例到 IQueryable<SpecificEntityObject> , SpecificEntityObject类型仅在运行时已知。

我们已尝试使用下面的代码,该代码无法编译,因为类型或命名空间 'objType' 不存在。

var t = query.ElementType;
Type objType = typeof(IQueryable<>).MakeGenericType(t);
var typed = query.Cast<IEnumerable<objType>>();


var grouped = typed.GroupByMany(groupBy.Select(grp => grp.Expression).ToArray());

有任何想法吗?

最佳答案

使用以下 IQueryable 扩展通用方法 query.ToDTO<sourceType,DestType>(); :

public static class QueryableExtensions
{
public static IQueryable<TDest> ToDTO<TSource, TDest>(this IQueryable<TSource> source)
{
List<TDest> destinationList = new List<TDest>();
List<TSource> sourceList = source.ToList<TSource>();

var sourceType = typeof(TSource);
var destType = typeof(TDest);
foreach (TSource sourceElement in sourceList)
{
TDest destElement = Activator.CreateInstance<TDest>();
//Get all properties from the object
PropertyInfo[] sourceProperties = typeof(TSource).GetProperties();
foreach (PropertyInfo sourceProperty in sourceProperties)
{
//and assign value to each propery according to property name.
PropertyInfo destProperty = destType.GetProperty(sourceProperty.Name);
destProperty.SetValue(destElement, sourceProperty.GetValue(sourceElement, null), null);
}
destinationList.Add(destElement);
}

return destinationList.AsQueryable();
}
}

关于c# - 将 IQueryable<EntityObject> 转换为 IQueryable<Specific>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8818938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com