【问题标题】:C# the best way to compare 4 strings and ignore the empty oneC#比较4个字符串并忽略空字符串的最佳方法
【发布时间】:2016-03-23 09:01:32
【问题描述】:

我想比较 4 个字符串是否相等。问题是我必须忽略空字符串,但是如果它们是 all 空的,那么该方法也必须返回true,因为所有空字符串都是相等的。我可以像

一样写下所有内容
if(string1 != string.Empty && string2 != string.Empty &&
               string1 != string2)
{
   return false
}
if(string1 != string.Empty && string2 != string.Empty &&  string3 != etc....

但我认为有一个比写出所有可能性更好的方法。 但是怎么做?

【问题讨论】:

  • 比较 4 个字符串:如何?订购它们,还是查看它们是否相等?
  • 您能否扩展一下您正在尝试做的事情?
  • 那么四个必须相等还是必须成对相等?此外,至少一项可以为空或根本不存在吗?
  • @Kimos 你肯定需要将它们放入数组中,那么这个答案会帮助你stackoverflow.com/questions/5307172/…
  • 所有字符串都应该相等。但如果它们都是空的,那么方法也必须返回 true,因为所有的空字符串都是相等的

标签: c#


【解决方案1】:

这将检查所有非空或非空字符串是否相等:

public static bool CheckNonEmptyStringsForEquality(params string[] strings)
{
    string target = strings.FirstOrDefault(s => !string.IsNullOrEmpty(s));

    if (target == null)
        return false;

    return strings.All(s => string.IsNullOrEmpty(s) || s == target);
}

像这样使用它:

Console.WriteLine(
    CheckNonEmptyStringsForEquality("", "X", "X")); // Prints true

Console.WriteLine(
    CheckNonEmptyStringsForEquality("", "X", "Y")); // Prints false

Console.WriteLine(
    CheckNonEmptyStringsForEquality("", "X", "", "X", "", "X", "")); // Prints true

注意:如果要在所有字符串为 null 或空的情况下返回 true,请改为:

public static bool CheckNonEmptyStringsForEquality(params string[] strings)
{
    string target = strings.FirstOrDefault(s => !string.IsNullOrEmpty(s));
    return strings.All(s => string.IsNullOrEmpty(s) || s == target);
}

那么这也将返回 true:

Console.WriteLine(
CheckNonEmptyStringsForEquality("", "", "")); // Prints true

【讨论】:

  • 没有用,当数组包含一个空字符串而其他字符串相等时,我得到了错误
  • @Kimos 发布不起作用的代码,我应该能够解释你做错了什么。如果您查看我上面给出的第一个用法示例,您可以看到当数组包含一个空字符串并且其他字符串相等时它返回 true。我发布的代码绝对有效。
【解决方案2】:

这样的?执行Distinct 并检查字符串数组中的Count

var strings = new string[] {"str1", "str2", "str3"};

if( (strings.Where(s=>!string.IsNullOrEmpty(s)).Distinct().Count() == 1))
{       
    // unique
}

【讨论】:

  • 问题不清楚,但我从示例中了解到,我们搜索“任意 2 个字符串”是否相等,而不是“全部”是否相等(意思是 strings.Distinct().Count() < strings.Count()
  • 查询是正确的,如果我们有相同的字符串,count 将为 1。
  • 所以我想我没听懂问题
【解决方案3】:

试试这个:

    static void Main(string[] args)
    {
        var text1 = new[] { "x", "y", "z", "w" };
        var text2 = new[] { "x", "y", null, "" };
        var text3 = new[] { "x", "x", "x", "x" };
        var text4 = new[] { "x", "x", null, "" };

        MyComparer(text1); // False
        MyComparer(text2); // False
        MyComparer(text3); // True
        MyComparer(text4); // True
    }

    private static bool MyComparer(IEnumerable<string> array)
    {
        return array.Where(t => !string.IsNullOrEmpty(t)).Distinct().Count() == 1;
    }

【讨论】:

  • var text5 = new[] { "", "", "", "" };返回 false,应该为 true 所有空字符串都是 euqal...
  • 我不认为问题说明它应该返回真或假。如果是这样,应该这样描述。
【解决方案4】:
        //Hope this helps
        string a = "";
        string b = "mystring";
        string c = "mystring";
        string d = "mystring";
        bool isEqual = true;
        ArrayList array = new ArrayList();
        array.Add(a);
        array.Add(b);
        array.Add(c);
        array.Add(d);


        foreach (string stringMemeber in array)
        {
            if (string.IsNullOrEmpty(stringMemeber))
            {
                continue;
            }
            else
            {
                foreach (string NestedStringMember in array)
                {
                    if (string.IsNullOrEmpty(NestedStringMember))
                    {
                        continue;
                    }
                    else
                    {
                        if (string.Compare(stringMemeber,NestedStringMember)!=0)
                        {
                            isEqual = false;
                            break;
                        }
                    }
                }

                if (!isEqual)
                {
                    break;
                }

            }
        }


        Console.WriteLine("The strings are equal: " + isEqual.ToString());

【讨论】:

  • 您可以使用单个循环检查数组中每个成员的相等性。不需要第二个foreach:它只是在做额外的工作。
【解决方案5】:

如果你在数组中传递字符串,

var collection = new string[] { "India", "", "India", "India" };
var isEqual = collection.Distinct().Contains("") ? collection.Distinct().Count() <= 2 : collection.Distinct().Count() == 1;

【讨论】:

  • 如果所有字符串都为空,这将导致 false,这是不正确的
  • 谢谢@Kimos。现在,即使所有字符串都是空的,代码也会返回 true
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多