![](/img/trans.png)
[英]How can I create a collection with a sequential number as one field from another collection in C#
[英]c# How can I create a collection of custom objects without going through each field
我創建了一個名為DataResponse
的類,該類具有40多個公共字段。 類DataResponse
具有與我的數據庫DataRepoes
的字段和類型相同的字段數和類型(假設是這樣)。
有什么辦法可以像linq一樣在下面創建對象列表並自動從數據庫中的字段中將字段分配給DataResponse
的方式? 否則,我必須拼寫出這40個字段中的每個字段,並在新建DataResponse類時手動分配它們。 謝謝
List<Classes.DataResponse> res = (from rx in con.DataRepoes
where iaccess.Contains(rx.STOREID)
select new Classes.DataResponse).ToList<Classes.DataResponse>();
您可以為此使用Automapper Queryable Extensions 。
假設Classes.DataResponse
的字段與DataRepoes
的字段具有相同的名稱,然后執行以下操作:
// During your application bootstrap, configure AutoMapper to create a map between the two types
Mapper.Initialize(cfg => cfg.CreateMap<DataRepoes, Classes.DataResponse);
// Then you can ask AutoMapper to project the IQueryable directly to your DTO
List<Classes.DataResponse> res = con.DataRepoes
.Where(rx => iaccess.Contains(rx.STOREID))
.ProjectTo<Classes.DataResponse>()
.ToList();
使用LINQ是不可能的。 但是,您可以使用“ AutoMapper ”來實現。 只需為這兩個類創建Map,然后將其映射
Mapper.CreateMap<DataResponse,DataRepo>();//Assuming DataRepoes is collection of DataRepo types
List<Classes.DataResponse> res = (from rx in con.DataRepoes
where iaccess.Contains(rx.STOREID)
select Mapper.Map<Classes.DataResponse>(rx)).
ToList<Classes.DataResponse>();
希望有幫助!!
如果您不需要AutoMapper提供的靈活性,或者不想使用第三方庫,則可以使用以下簡化的自定義擴展方法:
public static class QueryableExtensions
{
public static IQueryable<TResult> SelectTo<TResult>(this IQueryable source)
{
var sourceType = source.ElementType;
var resultType = typeof(TResult);
var parameter = Expression.Parameter(sourceType, "x");
var bindings =
from rm in resultType.GetProperties().Concat<MemberInfo>(resultType.GetFields())
join sm in sourceType.GetProperties().Concat<MemberInfo>(sourceType.GetFields())
on rm.Name equals sm.Name
select Expression.Bind(rm, Expression.MakeMemberAccess(parameter, sm));
var body = Expression.MemberInit(Expression.New(resultType), bindings);
return source.Provider.CreateQuery<TResult>(Expression.Call(
typeof(Queryable), "Select", new[] { sourceType, resultType },
source.Expression, Expression.Quote(Expression.Lambda(body, parameter))));
}
}
它將嘗試選擇所有與名稱匹配的屬性/字段。 如果匹配的屬性/字段類型不同,將失敗。
用法示例:
方法語法
var res = con.DataRepoes
.Where(rx => iaccess.Contains(rx.STOREID))
.SelectTo<Classes.DataResponse>()
.ToList();
查詢語法
var res =
(from rx in con.DataRepoes
where iaccess.Contains(rx.STOREID)
select rx)
.SelectTo<Classes.DataResponse>()
.ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.