【问题标题】:C# Multiple String Comparision with Same ValueC# 具有相同值的多个字符串比较
【发布时间】:2009-12-26 07:13:07
【问题描述】:

请看下面的案例,肯定会很有趣..

如果我想为多个对象分配相同的值,我会使用类似的东西

string1 = string2 = string3 = string 4 = "some string";

现在我想做的是,我想将 string1、string2、string3 和 string4 与“someotherstring”进行比较......问题是有没有办法在不写个人比较的情况下做到这一点。

string1 == "someotherstring" || string2 == "someotherstring" || string3 == "someotherstring" || string4 == "someotherstring"

希望我能够解释这个问题.. 请为此提供帮助。

问候, 帕雷什·拉索德

【问题讨论】:

  • 你想怎么写?

标签: c# string


【解决方案1】:

在 C# 3.0 中,你可以编写一个非常简单的扩展方法:

public static class StringExtensions
{
    public static bool In(this string @this, params string[] strings)
    {
        return strings.Contains(@this); 
    }
}

然后像这样使用它:

if ("some string".In(string1, string2, string3, string4))
{
    // Do something
}

【讨论】:

    【解决方案2】:

    对于你的情况,你可以尝试这样的事情

    if (new string[] { string1, string2, string3, string4 }.Contains("someotherstring"))
    {
    }
    

    【讨论】:

    • and 对于“and”操作:strings.All(x => x=="someotherstring")
    • 次要细节:在 C# 3.0 中,您可以通过省略数组的类型来进一步缩短语法(它将被推断)。即:if( new []{s1,s2,s3,s4}.Contains("s"))
    • 这给出了编译错误“无法访问私有方法'包含'这里”
    【解决方案3】:

    我发现 LINQ 非常有表现力,并且会考虑使用它来解决这个问题:

    new[] { string1, string2, string3, string4 }.Any(s => s == "some string")
    

    【讨论】:

      【解决方案4】:

      不,C# 中没有,但你可以这样写:

       (string1 == string2 && string2 == string3 && 
        string3 == string4 && string4 == "someotherstring")
      

      【讨论】:

      • 嗨詹姆斯..谢谢你的回复..如果你再看看我的问题..我用过||。意思是,string1、string2、string3 和 string4 中的任何一个都应该等于“someotherstring”......我认为......如果我想检查所有 4 个字符串实例是否都等于“someotherstring”,你的情况将适用?我对吗?问候, Paresh Rathod KlixMedia
      【解决方案5】:

      您可以创建一个简化阅读代码的函数:

      compareToFirst( "someotherthing", string1, string2, string3, string4);
      

      如果您想将此字符串列表与连续的“其他字符串”进行比较,您可能需要创建一个列表对象“myStringList”,在其中添加 string1/2/3/4,然后定义一个能够写

      compare( "someotherthing", myStringList );
      

      【讨论】:

        【解决方案6】:

        我不这么认为。你怎么知道哪一个没有比较或匹配。没有办法评估这种比较的副作用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-10-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-19
          相关资源
          最近更新 更多