【问题标题】:Python's 'in' operator equivalent to C#Python 的“in”运算符相当于 C#
【发布时间】:2011-06-27 22:46:46
【问题描述】:

使用 Python,我可以使用 'in' 运算符进行集合操作,如下所示:

x = ['a','b','c']
if 'a' in x:
  do something

C# 中的等价物是什么?

【问题讨论】:

  • 我不知道确切的语法,但我敢打赌你可以用 LINQ 做到这一点。
  • 这不是集合操作,因为那是列表而不是集合

标签: c# python operators


【解决方案1】:

大多数集合声明Contains 方法(例如通过ICollection<T> 接口),但总有更通用的LINQ Enumerable.Contains 方法:

char[] x = { 'a', 'b', 'c' };

if(x.Contains('a'))
{
   ...    
}

如果您认为这是“错误的方式”,您可以编写一个扩展来纠正问题:

public static bool In<T>(this T item, IEnumerable<T> sequence)
{
   if(sequence == null)
      throw new ArgumentNullException("sequence");

   return sequence.Contains(item);    
}

并将其用作:

char[] x = { 'a', 'b', 'c' };

if('a'.In(x))
{
   ...    
}

【讨论】:

  • 或者 ContainsKey 如果x 是字典。
  • 为什么sequence == null会引发异常,应该只返回false
  • @David Heffernan:这是一个选项,但在 .NET 中,容器类型的 null 引用通常用于表示容器本身的 不存在比一个 empty 容器。如果我们假设该约定;第二个参数为 null 确实是一个错误。
  • @Ani 很公平,我对 .net 约定知之甚少。有人想知道,如果 sequence == null 不是有效输入,为什么不让代码前进到 sequence.Contains
  • @David:Python 的in 运算符会为None 序列抛出异常,因此这是预期的行为。
【解决方案2】:

要基于Ani 的答案,Python 的字典in 运算符相当于C# 中的ContainsKey,因此您需要两种扩展方法:

public static bool In<T, V>(this T item, IDictionary<T, V> sequence)
{
    if (sequence == null) throw new ArgumentNullException("sequence");
    return sequence.ContainsKey(item);
}

public static bool In<T>(this T item, IEnumerable<T> sequence)
{
    if (sequence == null) throw new ArgumentNullException("sequence");
    return sequence.Contains(item);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 2011-06-05
    • 2012-07-20
    • 2012-04-23
    • 1970-01-01
    相关资源
    最近更新 更多