这是使用 LINQ 查询语法分配属性的更短方法吗?
Is that a shorter way assigning properties with LINQ Query Syntax?
假设我有一个包含 30 个属性的对象列表(例如:Items
)
如果我将 LINQ 查询语法用于 Join
另一个对象(例如:Store
),我似乎不可避免地必须从 Item
,对吧?
例如:
var temp = from a in items
join b in stores on a.storeKey = b.storeKey into b2
from c in b2.DefaultIfEmpty()
select new ItemViewModel()
{
p1 = a.p1,
p2 = a.p2,
....
p30 = a.p2, //re-assign 30 times (T.T)
storeInfo1 = c.storeInfo1 //all i want is 1 or 2 additional info from store
}
您可以使用 AutoMapper 等库。对于 a
和 ItemViewModel
之间相同的 属性 名称,它可以使用反射为您进行映射,对于具有不同名称的属性,您可以定义手动映射,对于来自的属性其他对象(b 和 c)你可以使用助手。
像这样:
var temp = from a in items
join b in stores on a.storeKey = b.storeKey into b2
from c in b2.DefaultIfEmpty()
select CreateModelFrom(a, b, c);
public ItemViewModel CreateModelFrom(ObjA a, ObjB b, ObjC c)
{
var model = Mapper.Map<ObjA, ItemViewModel>();
model.xxx = b.xxx;
model.storeInfo1 = c.storeInfo1;
return model;
}
看到要求,我认为您应该更改 class 结构。他们有两种方式
- ItemViewModel 应派生自与项目相同的 class 或
- 里面应该有一个属性
我写的是第二种方式
class Item
{
string p1;
......
}
class ItemViewModel
{
string p1;
......
string storeInfo1;
Item item;
ItemViewModel(Item item, string storeInfo)
{
this.item= item;
this.storeInfo1 = storeInfo;
}
}
var temp = from a in items
join b in stores on a.storeKey = b.storeKey into b2
from c in b2.DefaultIfEmpty()
select new ItemViewModel(a, c.storeInfo1);
假设我有一个包含 30 个属性的对象列表(例如:Items
)
如果我将 LINQ 查询语法用于 Join
另一个对象(例如:Store
),我似乎不可避免地必须从 Item
,对吧?
例如:
var temp = from a in items
join b in stores on a.storeKey = b.storeKey into b2
from c in b2.DefaultIfEmpty()
select new ItemViewModel()
{
p1 = a.p1,
p2 = a.p2,
....
p30 = a.p2, //re-assign 30 times (T.T)
storeInfo1 = c.storeInfo1 //all i want is 1 or 2 additional info from store
}
您可以使用 AutoMapper 等库。对于 a
和 ItemViewModel
之间相同的 属性 名称,它可以使用反射为您进行映射,对于具有不同名称的属性,您可以定义手动映射,对于来自的属性其他对象(b 和 c)你可以使用助手。
像这样:
var temp = from a in items
join b in stores on a.storeKey = b.storeKey into b2
from c in b2.DefaultIfEmpty()
select CreateModelFrom(a, b, c);
public ItemViewModel CreateModelFrom(ObjA a, ObjB b, ObjC c)
{
var model = Mapper.Map<ObjA, ItemViewModel>();
model.xxx = b.xxx;
model.storeInfo1 = c.storeInfo1;
return model;
}
看到要求,我认为您应该更改 class 结构。他们有两种方式
- ItemViewModel 应派生自与项目相同的 class 或
- 里面应该有一个属性
我写的是第二种方式
class Item
{
string p1;
......
}
class ItemViewModel
{
string p1;
......
string storeInfo1;
Item item;
ItemViewModel(Item item, string storeInfo)
{
this.item= item;
this.storeInfo1 = storeInfo;
}
}
var temp = from a in items
join b in stores on a.storeKey = b.storeKey into b2
from c in b2.DefaultIfEmpty()
select new ItemViewModel(a, c.storeInfo1);