代码之家  ›  专栏  ›  技术社区  ›  Pawan Nogariya

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

  •  0
  • Pawan Nogariya  · 技术社区  · 3 年前

    我有一个返回的查询 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
        });
    

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

    如果我能使用外部函数,这本可以用一种非常漂亮的方式来实现,但我不能,因为它在 易读的

    我有一个无法克服的限制 IEnumerable ,我必须在 易读的 仅限于表格。

    考虑到这些局限性,有什么办法可以对这段丑陋的代码进行简化吗?

    0 回复  |  直到 3 年前
        1
  •  -2
  •   YD9    3 年前

    可以将映射提取到 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();