将两个列表合并为一个

将两个列表合并为一个

本文介绍了将两个列表合并为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个类似以下的列表:

I have 2 list like following:

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将它们合并到一个列表中,如果ProductItemTypeIdProductIdProductItemId NOT 0.我已经做到了,但是使用foreach如下:

I want to be able to merge them into a single list using Linq using my custom logic which would be to keep only the objects if ProductItemTypeId matches where ProductId or ProductItemId is NOT 0. I have achieved this but using foreach like below:

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中编写上述逻辑,以使我的代码更简洁,我将不胜感激.

I would really appreciate if anyone can suggest how I can write the above logic in Linq so that my code is more concise.

推荐答案

据此:

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

这篇关于将两个列表合并为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 11:48