如何在C#

时间:2019-03-05 11:37:09

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

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

我想删除空格的列,特殊字符是咨询=咨询。名称

我正在使用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"

                     });

2 个答案:

答案 0 :(得分:4)

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

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

使用名称空间

using System.Text.RegularExpressions;

答案 1 :(得分: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"

                     });