集中或整合LINQ选择

时间:2015-01-07 03:13:06

标签: c# linq

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

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需要改变,比如添加一个新的领域,其他情况就是&#39;投影可能彼此不一致(忘记或错过更新)。我该如何集中这个?

3 个答案:

答案 0 :(得分:3)

你可以这样做:

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

答案 1 :(得分:2)

你能这样做吗?

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

答案 2 :(得分:1)

这种方法有帮助吗?

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