集中或合并 LINQ 选择

本文关键字:选择 LINQ 合并 集中 | 更新日期: 2023-09-27 18:36:35

如何重构此代码以便集中投影?

public IEnumerable<ItemDto> GetItemsByType(int itemId, ItemType itemType)
{
    IEnumerable<ItemDto> items = null;
    try
    {
        var tempItems= _Items.Get(i => i.ItemId == itemId
            && o.Active == true);
        switch (itemType)
        {
            case ItemType.Normal:
                items = from item in tempItems
                        select new ItemDto
                        {
                            // many fields here
                        };
                break;
            case ItemType.Damaged:
                items = from item in tempItems
                        join itemDetail in _ItemDetails.Get() on item.ID equals itemDetail.ItemID
                        select new ItemDto
                        {
                            // many fields here
                        };
                break;
            case ItemType.Fixed:
                items = from item in tempItems
                        join itemDetail in _ItemDetails.Get() on item.ID equals itemDetail.ItemID
                        where item.Status.ToLower() == "fixed"
                        select new ItemDto
                        {
                            // many fields here
                        };
                break;
            // more case statements here...
            default:
                break;
        }
    }
    catch { ... }
}

基本上,我有很多案例陈述,每个案例陈述都有一个很长的投影。我担心一旦 DTO 需要更改,例如添加新字段,其他情况的预测可能彼此不一致(忘记或错过更新)。我怎样才能集中起来?

集中或合并 LINQ 选择

你可以做这样的事情:

var baseQuery = from item in tempItems select item;
switch (itemType)
{
     case ItemType.Fixed:
         baseQuery = from item in baseQuery where item.ID equals itemID select item;
         break;
}
return (from item in baseQuery select new ItemDTO (...projection here... ));

你能这样处理吗?

var query = tempItems.AsQueryable();
switch(itemType)
{
   case ItemType.Damaged:
        query.Join(...);
        break;
   case ItemType.Fixed:
        query.Where(...);
}
query.Select(e => new ItemDto{//Lots of properties});
return query.ToList();

这种方法会有帮助吗?

public IEnumerable<ItemDto> GetItemsByType2(int itemId, ItemType itemType)
{
    var cases = new Dictionary<ItemType, Func<IEnumerable<ItemDto>, IEnumerable<ItemDto>>>()
    {
        { ItemType.Normal, xs => xs },
        { ItemType.Damaged, xs =>
            from item in xs
            join itemDetail in _ItemDetails.Get() on item.ID equals itemDetail.ItemID
            select item },
        { ItemType.Fixed, xs =>
            from item in xs
            join itemDetail in _ItemDetails.Get() on item.ID equals itemDetail.ItemID
            where item.Status.ToLower() == "fixed"
            select item },
    };
    return cases[itemType](_Items.Get(i => i.ItemId == itemId && o.Active == true))
        .Select(x => new ItemDto { .... });
}