【问题标题】:I want to compare a String that gets modified to its default我想将修改后的字符串与其默认值进行比较
【发布时间】:2022-01-28 21:50:15
【问题描述】:

我正在编写一种从 .csv 文件中排除元字段的方法。

  public static string metaField(this string test)
    {
        String[] excludeMetafield = { "metafield_1000", "metafield_1001", "metafield_item_1_content_2", "metafield_short_description" };
        String testing = "";

        if (excludeMetafield.Contains(test) || excludeMetafield.Equals(test))
        {
            return test;
        }
        return testing = "Failed";
    }

string test 被传递到方法中时,例如"short_description",但是当将值写入.csv 文件时,它会被修改为"metafield_short_description"

我的.Contains 没有检测到"metafield_short_description" 包含 "short_description"。我该怎么做?

【问题讨论】:

  • 这个方法被修改用于测试,看它是否检测到字符串何时包含该文本。

标签: c# string csv contains


【解决方案1】:

您当前正在检查数组是否包含您的确切值。您实际上需要遍历您的检查字符串并检查迭代的String 物理上是否包含您的值。

  public static string metaField(this string test)
    {
        String[] excludeMetafield = { "metafield_1000", "metafield_1001", "metafield_item_1_content_2", "metafield_short_description" };
        String testing = "";

        foreach (string s in excludeMetafield) {
            if (s.Contains(test) || s.Equals(test))
            {
                return test;
            }
        }
        return testing = "Failed";
    }

【讨论】:

    【解决方案2】:

    你可以使用 linq

    var excludeMetafield =  new string[] { "metafield_1000", "metafield_1001", "metafield_item_1_content_2", "metafield_short_description" };
    
    if (excludeMetafield.Any(e=>e.Contains(test))) return test; 
    return "Failed";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多