【发布时间】:2014-04-01 00:33:37
【问题描述】:
我有 2 个如下列表:
var selectedItems = _uow.ProductItems.Get(w => w.ProductId == productid).Select(projection => new
{
ProductId = projection.ProductId,
ProductItemId = projection.ProductItemId,
ProductItemTypeId = projection.ProductItemTypeId,
ProductItemName = GetItemName(projection),
ProductItemType = projection.ItemType,
Amount = projection.Amount
});
var services = _uow.Services.GetAll().Select(projection => new {
ProductId = 0,
ProductItemId = 0,
ProductItemTypeId = projection.ServiceId,
ProductItemName = projection.Name,
ProductItemType = "Service",
Amount = projection.DefaultAmount
});
我希望能够使用Linq 使用我的自定义逻辑将它们合并到一个列表中,如果ProductItemTypeId 匹配其中ProductId 或ProductItemId 是NOT0。我已经实现了这一点,但使用foreach,如下所示:
List<dynamic> productItems = new List<dynamic>();
foreach (var item in services)
{
if (item.ProductItemTypeId == selectedItems.Select(s => s.ProductItemTypeId).FirstOrDefault())
{
productItems.Add(selectedItems.Where(w => w.ProductItemTypeId == item.ProductItemTypeId).FirstOrDefault());
}
else
{
productItems.Add(item);
}
}
如果有人能建议我如何在Linq 中编写上述逻辑,我将不胜感激,这样我的代码会更简洁。
【问题讨论】:
-
只是在黑暗中拍摄,也许你可以试试Union
-
@Noobacode 感谢您的评论,但请参阅下面我对
Zip的评论