Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centralizing or consolidating LINQ select

Tags:

c#

linq

How do I refactor this code so I can centralize the projection?

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

Basically, I have lots of case statements and a long projection on each case statement. I'm worried that once the DTO needs to change, say add a new field, the other cases' projection might not be consistent with each other (forgot or missed updating). How can I centralize this?

like image 257
g_b Avatar asked Jan 07 '15 03:01

g_b


1 Answers

You could do something like this:

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... ));
like image 123
user92454 Avatar answered Oct 27 '22 17:10

user92454