Centralizing or consolidating LINQ choices

How do I reorganize this code so that 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 many case arguments and a long projection onto each case statement. I am worried that as soon as the DTO needs to be changed, say, add a new field, the projection of other cases may not correspond to each other (forgot or missed the update). How can I centralize this?

+6
source share
3 answers

Could you come up like that?

 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
source

You can 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... )); 
+3
source

Would such an approach help?

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

Source: https://habr.com/ru/post/980627/


All Articles