【问题标题】:How to remove spaces from linq data in C#如何从 C# 中的 linq 数据中删除空格
【发布时间】:2019-03-05 11:37:08
【问题描述】:

我有 linq,其中一列中的数据可能在字符串之间有空格或特殊字符,例如我的调查,你的调查。我需要删除它,所以过滤 linq 后应该返回 mysurvey 和 yourssurvey

列我有兴趣删除空格和特殊字符是consultation =consultation.Name

我正在使用 C# .net 核心和实体框架

      var query = (from consultation in Context.Consultations
                     join survey in Context.Surveys on consultation.Id equals survey.ConsultationId into surveys
                     select new 
                     {
                         consultationId = consultation.Id,
                         consultation = consultation.Name,
                         surveyId = surveys.FirstOrDefault() == null? null : surveys.Select(x=>x.Id),
                         survey = surveys.FirstOrDefault() == null ? null : surveys.Select(x => x.Name),
                         subject ="survey"

                     });

【问题讨论】:

  • LINQ 只是一种查询语言。这不是 ORM。您使用的是哪个 ORM,为什么不使用 relations?从关系和导航属性生成 JOIN 是 ORM 的工作。除了from cons in Context.Consultations from survey in cons.Surveys ....,你不需要写任何东西
  • 或者你可以写from survey in Context.Surveys select new { survey.Consultation.ID, survey.ID...}
  • 我正在使用实体框架

标签: c# entity-framework linq .net-core


【解决方案1】:

如果您想删除字符串中的空格和特殊字符,请使用如下:

consultation = Regex.Replace(consultation.Name, "[^0-9A-Za-z]+", "");

使用命名空间

using System.Text.RegularExpressions;

【讨论】:

  • 这行不通。正则表达式不能作为可查询的,只能作为可枚举的,这是预期的,因为 reqex 代码不能被翻译成 SQL。如果您想使用正则表达式,您首先必须将选定的属性(包括不需要的字符)移动到本地进程(AsEnumerable),然后才能使用包含 Reqex 的新 Select
【解决方案2】:

像这样写一个扩展方法

public static string StripSpacesAndSpecialCharacters(this string text)
{
   var specChars = new string[] { "'", ";" }; // add more spec chars here
            var procesesedString = text.Trim();

   foreach (var spec in specChars)
   {
     procesesedString = procesesedString.Replace(spec, string.Empty);
   }
   return procesesedString;
}

然后在您的查询中使用它,例如

var query = (from consultation in Context.Consultations
                     join survey in Context.Surveys on consultation.Id equals survey.ConsultationId into surveys
                     select new 
                     {
                         consultationId = consultation.Id,
                         consultation = consultation.Name.StripSpacesAndSpecialCharacters(),
                         surveyId = surveys.FirstOrDefault() == null? null : surveys.Select(x=>x.Id),
                         survey = surveys.FirstOrDefault() == null ? null : surveys.Select(x => x.Name),
                         subject ="survey"

                     });

【讨论】:

    猜你喜欢
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多