将两个列表合并为一个

时间:2014-02-28 06:28:01

标签: c# linq list dynamic

我有以下两个列表:

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或{{1},则只保留对象是 ProductItemId。我已经实现了这一点,但使用0如下所示:

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); } } 中编写上述逻辑以便我的代码更简洁,我将非常感激。

2 个答案:

答案 0 :(得分:1)

您可以将Zip与Linq一起使用。

Enumerable.Zip<TFirst, TSecond, TResult>

这将生成两个联合的新列表。

http://msdn.microsoft.com/es-es/library/dd267698(v=vs.110).aspx

我希望这会有所帮助

编辑:尝试这样的事情:

var listResult = list1.Where(x => x.ProductId == 0 || x.ProductItemId == 0).Concat(list2.Where(x => x.ProductId == 0 || x.ProductItemId == 0));

答案 1 :(得分:0)

根据这个:

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);
    }
}

您可以使用left join代替:

var query = (from service in services
             join item in selectedItems
                 on service.ProductItemTypeId equals item.ProductItemTypeId
                 into joinedList
             from item in joinedList.DefaultIfEmpty()
             select new
             {
                 ProductId = item != null ? item.ProductId : service.ProductId,
                 ProductItemId = item != null ? item.ProductItemId :  service.ProductItemId,
                 ProductItemTypeId = item != null ? item.ProductItemTypeId : service.ProductItemTypeId,
                 ProductItemName = item != null ? item.ProductItemName : service.ProductItemName,
                 ProductItemType = item != null ? item.ProductItemType : service.ProductItemType,
                 Amount = item != null ? item.Amount : service.Amount
             })
             .ToList();