有没有办法在IQueryable中使用外部函数或简化字符串操作



我有一个返回IQueryable的查询。

return _staffQueryService.ClearAllFilters().OnlyActiveStaff().ExcludeContractors()
.Get().Select(s => new AutoCompleteItem
{
Value = s.PersonnelNumber,
Text = s.FullName +
(string.IsNullOrEmpty((string.IsNullOrWhiteSpace(s.SectionCode) ? null : s.SectionCode) ?? (string.IsNullOrWhiteSpace(s.DivisionCode) ? null : s.DivisionCode)) ? string.Empty : " (") +
((string.IsNullOrWhiteSpace(s.SectionCode) ? null : s.SectionCode) ?? (string.IsNullOrWhiteSpace(s.DivisionCode) ? null : s.DivisionCode)) +
(string.IsNullOrEmpty((string.IsNullOrWhiteSpace(s.SectionCode) ? null : s.SectionCode) ?? (string.IsNullOrWhiteSpace(s.DivisionCode) ? null : s.DivisionCode)) ? string.Empty : ")") +
(string.IsNullOrEmpty(s.FirstPhoneNumber ?? s.SecondPhoneNumber) ? string.Empty : " (") +
(string.IsNullOrEmpty(s.FirstPhoneNumber ?? s.SecondPhoneNumber) ? string.Empty : ("x" + (s.FirstPhoneNumber ?? s.SecondPhoneNumber))) +
(string.IsNullOrEmpty(s.FirstPhoneNumber ?? s.SecondPhoneNumber) ? string.Empty : ")"),
Email = s.Email
});

正如您所看到的,我不得不使用大量难看的字符串操作来准备输出。我不得不多次重复所有的字符串检查。

如果我可以使用外部函数,这可以用一种非常漂亮的方式来完成,但我不能使用,因为它在IQueryable上下文中。

我有一个限制,我不能将其强制转换为IEnumerable,我只能以IQueryable的形式返回结果。

考虑到这些限制,有什么可以对这个丑陋的代码做些什么来简化它吗?

您可以提取到func委托的映射,并将其用作选择器。

Func<MyModel, AutoCompleteItem> selector = s => new AutoCompleteItem
{
Value = s.PersonnelNumber,
Text = s.FullName +
(string.IsNullOrEmpty((string.IsNullOrWhiteSpace(s.SectionCode) ? null : s.SectionCode) ?? (string.IsNullOrWhiteSpace(s.DivisionCode) ? null : s.DivisionCode)) ? string.Empty : " (") +
((string.IsNullOrWhiteSpace(s.SectionCode) ? null : s.SectionCode) ?? (string.IsNullOrWhiteSpace(s.DivisionCode) ? null : s.DivisionCode)) +
(string.IsNullOrEmpty((string.IsNullOrWhiteSpace(s.SectionCode) ? null : s.SectionCode) ?? (string.IsNullOrWhiteSpace(s.DivisionCode) ? null : s.DivisionCode)) ? string.Empty : ")") +
(string.IsNullOrEmpty(s.FirstPhoneNumber ?? s.SecondPhoneNumber) ? string.Empty : " (") +
(string.IsNullOrEmpty(s.FirstPhoneNumber ?? s.SecondPhoneNumber) ? string.Empty : ("x" + (s.FirstPhoneNumber ?? s.SecondPhoneNumber))) +
(string.IsNullOrEmpty(s.FirstPhoneNumber ?? s.SecondPhoneNumber) ? string.Empty : ")"),
Email = s.Email
};

你可以这样使用它:

_staffQueryService.ClearAllFilters().OnlyActiveStaff().ExcludeContractors()
.Get().Select(selector).AsQueryable();

最新更新