用C#多字符串比较 [英] Multiple string comparison with C#

查看:202
本文介绍了用C#多字符串比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我需要比较,如果串x是A,B或C。



使用Python中,我可以在运营商使用检查这一点很容易

 如果x在[A,b,C]:
做什么

在C#中,我可以做

 如果(的String.Compare(X,A,StringComparison.OrdinalIgnoreCase)|| ...)
做些什么

它可以更类似于Python的东西吗?



ADDED



我需要为了使用不区分大小写添加 System.Linq的包含()。

 使用系统; 
使用System.Linq的;
使用System.Collections.Generic;

类你好{
公共静态无效的主要(){
变种x =A;

无功串=新的List<串GT; {一,B,C};
如果(strings.Contains(X,StringComparer.OrdinalIgnoreCase)){
Console.WriteLine(你好);
}
}
}

 使用系统; 
使用System.Linq的;
使用System.Collections.Generic;

静态类你好{
公共静态布尔在(这串源,则params字符串[]列表)
{
如果(空==源)抛出新ArgumentNullException (资源);
返回list.Contains(来源StringComparer.OrdinalIgnoreCase);
}

公共静态无效的主要(){
字符串x =A;

如果(x.In(一,B,C)){
Console.WriteLine(你好);
}
}
}


解决方案

使用 Enumerable.Contains< T> 这是的IEnumerable℃的扩展方法; T>

  VAR串=新的List<串GT; {A,B,C}; 
字符串x = //一些字符串
布尔包含= strings.Contains(X,StringComparer.OrdinalIgnoreCase);
如果(含){
//做些什么
}


Let's say I need to compare if string x is "A", "B", or "C".

With Python, I can use in operator to check this easily.

if x in ["A","B","C"]:
    do something

With C#, I can do

if (String.Compare(x, "A", StringComparison.OrdinalIgnoreCase) || ...)
    do something

Can it be something more similar to Python?

ADDED

I needed to add System.Linq in order to use case insensitive Contain().

using System;
using System.Linq;
using System.Collections.Generic;

class Hello {
    public static void Main() {
        var x = "A";

        var strings = new List<string> {"a", "B", "C"};
        if (strings.Contains(x, StringComparer.OrdinalIgnoreCase)) {
            Console.WriteLine("hello");
        }
    }
}

or

using System;
using System.Linq;
using System.Collections.Generic;

static class Hello {
    public static bool In(this string source, params string[] list)
    {
        if (null == source) throw new ArgumentNullException("source");
        return list.Contains(source, StringComparer.OrdinalIgnoreCase);
    }

    public static void Main() {
        string x = "A";

        if (x.In("a", "B", "C")) {
            Console.WriteLine("hello");
        }
    }
}

解决方案

Use Enumerable.Contains<T> which is an extension method on IEnumerable<T>:

var strings = new List<string> { "A", "B", "C" };
string x = // some string
bool contains = strings.Contains(x, StringComparer.OrdinalIgnoreCase);
if(contains) {
    // do something
}

这篇关于用C#多字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆