C
C#2y ago
Zigo

❔ How bad is this Linq code?

if (getBeginningContent == false)
dynContentList = await _context.DynamicContents
.OrderBy(x => x.OrderIndex)
.Where(i => !i.Name.Contains("resume-header"))
.Where(i => !i.Name.Contains("navbar"))
.Where(i => !i.Name.Contains("social-media"))
.Where(i => !i.Name.Contains("resume-info-cards"))
.Select(d => new DynamicContentDTO(d))
.ToListAsync();
else
dynContentList = await _context.DynamicContents
.OrderBy(x => x.OrderIndex)
//.Where(i => strArray.Any(i.Name.Contains))
//.Where(i => strArray.Any(s => i.Name.Contains(s)))
.Where(i => i.Name.Contains("resume-header") ||
i.Name.Contains("navbar") ||
i.Name.Contains("social-media") ||
i.Name.Contains("resume-info-cards"))
.Select(d => new DynamicContentDTO(d))
.ToListAsync();
if (getBeginningContent == false)
dynContentList = await _context.DynamicContents
.OrderBy(x => x.OrderIndex)
.Where(i => !i.Name.Contains("resume-header"))
.Where(i => !i.Name.Contains("navbar"))
.Where(i => !i.Name.Contains("social-media"))
.Where(i => !i.Name.Contains("resume-info-cards"))
.Select(d => new DynamicContentDTO(d))
.ToListAsync();
else
dynContentList = await _context.DynamicContents
.OrderBy(x => x.OrderIndex)
//.Where(i => strArray.Any(i.Name.Contains))
//.Where(i => strArray.Any(s => i.Name.Contains(s)))
.Where(i => i.Name.Contains("resume-header") ||
i.Name.Contains("navbar") ||
i.Name.Contains("social-media") ||
i.Name.Contains("resume-info-cards"))
.Select(d => new DynamicContentDTO(d))
.ToListAsync();
4 Replies
Angius
Angius2y ago
The fact that names can contain all those various things makes me think you could replace it by a separate enum column Even index it for a faster lookup
cap5lut
cap5lut2y ago
i would add { } blocks, like that it looks weird/error prone. and i would reverse the filtering and ordering, no need to order stuff u throw out afterwards. if (getBeginningContent == false) can be rewritten to if (!getBeginningContent)
and i would reverse the filtering and ordering, no need to order stuff u throw out afterwards.
not sure if that applies for ef as well tho
Anton
Anton2y ago
yes, because there is duplicate code. you could solve it, but the solution is likely going to be more complicated than copy pasting it once. if you find this logic appearing in multiple places, create a helper function that creates an appropriate expression tree out of those individual strings. as it stands, you can also try using a string array and check if any element is equal to your item name, that should also work. Then just negating the condition will suffice, you won't have to copy paste the strings ah yes like you're doing in the commented out code. if that doesn't work, build the expression tree
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.