【问题标题】:Remove spaces and underscores from a T List从 T 列表中删除空格和下划线
【发布时间】:2017-03-17 09:50:44
【问题描述】:

问题: T 对象列表 (aTSource) 包含字段名称列表,其中包含额外的空格和下划线,以防止与没有的变量匹配。

我的模型类中有一个 T 对象列表。此列表包括字段名称、值和字段类型。我想进入字段名称并删除名称中的所有空格和下划线。

代码的目的是比较 Excel 文档和 WPF 表单中的字段,并返回这些字段名称的共同列表。

foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
{
    T aTSource = new T();
    foreach (PropInfo aField in commonFields)
    {
        PropertyInfo propertyInfos = aTSource.GetType().GetProperty(aField.Name);
        var value = (dataRow[afield.Name] == DBNull.Value) ? null : dataRow[afield.Name]; 
        ...     
        propertyInfos.SetValue(aTSource, value, null);
        list.Add(aTSource);
    }
}

来自 aTSource 的示例值:

IP_Address     null  string
Product Name   null  string

【问题讨论】:

    标签: c# excel wpf removing-whitespace


    【解决方案1】:

    使用替换语句创建两个 Foreach 循环,第一个用于 Excel 字段名称列表,第二个用于 WPF 形式的字段名称,以确保字段名称都匹配。

    foreach (DataColumn column in dataTable.Columns)
    {
        column.ColumnName = column.ColumnName.Replace(" ", "");
        column.ColumnName = column.ColumnName.Replace("_", "");
    }
    

    【讨论】:

      【解决方案2】:

      如果您的目标只是比较两个字符串,独立于空格和下划线,您可以创建一个扩展方法来去除它们然后进行比较:

      public static string SuperStrip(this string InputString)
      {
          if (string.IsNullOrWhiteSpace(InputString))
              return string.Empty;
      
          return InputString.Replace(" ", string.Empty).Replace("_", string.Empty);
      }
      

      每个表达式都会产生true 条件:

      bool foo;
      foo = "nicekitty".SuperStrip() == "nice kitty".SuperStrip();
      foo = "nicekitty".SuperStrip() == "nice_kitty".SuperStrip();
      foo = "nice_kitty".SuperStrip() == "nice kitty".SuperStrip();
      

      当然,您也可以将其封装在一个函数中进行比较:

      public static bool HeaderCompare(string String1, string String2)
      {
          if (string.IsNullOrWhiteSpace(String1))
              String1 = string.Empty;
          if (string.IsNullOrWhiteSpace(String2))
              String2 = string.Empty;
      
          return String1.Replace(" ", string.Empty).Replace("_", string.Empty) ==
              String2.Replace(" ", string.Empty).Replace("_", string.Empty);
      }
      

      这似乎过于简单了,所以我可能误解了你的任务,所以如果我离开了,请随时告诉我。

      【讨论】:

      • 感谢您的建议,但是,我真的在寻找一种方法来更改 T 列表的字段名称。 “IP_Address”将变为“IPAddress”,“Product Name”将变为“ProductName”。我最终解决了这个问题,用另一个字符“^”替换下划线和空格,然后对这个新字符进行比较。
      猜你喜欢
      • 1970-01-01
      • 2022-08-12
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      • 2019-11-25
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多