检查值是否在数组中(C#)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13257458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 07:57:58  来源:igfitidea点击:

Check if a value is in an array (C#)

c#.netarraysstring

提问by Cecil Rodriguez

How do I check if a value is in an array in C#?

如何检查值是否在 C# 中的数组中?

Like, I want to create an array with a list of printer names.

就像,我想创建一个包含打印机名称列表的数组。

These will be fed to a method, which will look at each string in turn, and if the string is the same as a value in an array, do that action.

这些将被提供给一个方法,该方法将依次查看每个字符串,如果字符串与数组中的值相同,则执行该操作。

For example:

例如:

string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
foreach (p in printer)
{
   PrinterSetup(p);     
}

These are the names of the printers, they are being fed to the PrinterSetup method.

这些是打印机的名称,它们被提供给 PrinterSetup 方法。

PrinterSetup will look sort of like this (some pseudocode):

PrinterSetup 看起来像这样(一些伪代码):

public void PrinterSetup(printer)
{
   if (printer == "jupiter") 
   {
      Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
   }
}

How do I format if (printer == "jupiter")in a way that C# can recognize?

如何if (printer == "jupiter")以 C# 可以识别的方式进行格式化?

采纳答案by Dmytro

Add necessary namespace

添加必要的命名空间

using System.Linq;

Then you can use linq Contains()method

然后你可以使用 linqContains()方法

string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains("jupiter"))
{
    Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
}

回答by Dmytro

You are just missing something in your method:

你只是在你的方法中遗漏了一些东西:

public void PrinterSetup(string printer)
{
   if (printer == "jupiter") 
   {
      Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
   }
}

Just add stringand you'll be fine.

只需添加string,你会没事的。

回答by code4life

Something like this?

像这样的东西?

string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
PrinterSetup(printer);

// redefine PrinterSetup this way:
public void PrinterSetup(string[] printer)
{
    foreach (p in printer.Where(c => c == "jupiter"))
    {
        Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
    }
}

回答by Brandon Moretz

Not very clear what your issue is, but it sounds like you want something like this:

不太清楚您的问题是什么,但听起来您想要这样的东西:

    List<string> printer = new List<string>( new [] { "jupiter", "neptune", "pangea", "mercury", "sonic" } );

    if( printer.Exists( p => p.Equals( "jupiter" ) ) )
    {
        ...
    }

回答by Raz Megrelidze

    public static bool Contains(Array a, object val)
    {
        return Array.IndexOf(a, val) != -1;
    }

回答by Raz Megrelidze

   string[] array = { "cat", "dot", "perls" };

// Use Array.Exists in different ways.
bool a = Array.Exists(array, element => element == "perls");
bool b = Array.Exists(array, element => element == "python");
bool c = Array.Exists(array, element => element.StartsWith("d"));
bool d = Array.Exists(array, element => element.StartsWith("x"));

// Display bools.
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
----------------------------output-----------------------------------

1)True 2)False 3)True 4)False

1)正确 2)错误 3)正确 4)错误

回答by Guest

if ((new [] {"foo", "bar", "baaz"}).Contains("bar"))
{

}  

回答by Sergey Brunov

Consider using HashSet<T>Classfor the sake of lookup performance:

为了查找性能考虑使用HashSet<T>Class

This method is an O(1) operation.

HashSet<T>.ContainsMethod (T), MSDN.

该方法是一个 O(1) 操作。

HashSet<T>.Contains方法 (T),MSDN

For example:

例如:

class PrinterInstaller
{
    private static readonly HashSet<string> PrinterNames = new HashSet<string>
        {
            "jupiter", "neptune", "pangea", "mercury", "sonic"
        };

    public void Setup(string printerName)
    {
        if (!PrinterNames.Contains(printerName))
        {
            throw new ArgumentException("Unknown printer name", "printerName");
        }
        // ...
    }
}

回答by Ricardo Fercher

I searched now over 2h to find a nicely way how to find duplicatesin a list and how to remove them. Here is the simplest answer:

我现在搜索了 2 小时以上,以找到一种很好的方法,即如何在列表中查找重复项以及如何删除它们。这是最简单的答案:

//Copy the string array with the filtered data of the analytics db into an list
// a list should be easier to use
List<string> list_filtered_data = new List<string>(analytics_db_filtered_data);

// Get distinct elements and convert into a list again.
List<string> distinct = list_filtered_data.Distinct().ToList();

The Output will look like this: Duplicated Elements will be removed in the new list called distinct!

输出将如下所示: 重复元素将在名为 distinct 的新列表中删除!

回答by Philm

Note: The question is about arrays of strings. The mentioned routines are not to be mixed with the .Contains method of single strings.

注意:问题是关于字符串数组。上述例程不能与单个字符串的 .Contains 方法混合使用。

I would like to add an extending answer referring to different C# versions and because of two reasons:

我想添加一个涉及不同 C# 版本的扩展答案,原因有两个:

  • The accepted answer requires Linq which is perfectly idiomatic C# while it does not come without costs, and is not available in C# 2.0 or below. When an array is involved, performance may matter, so there are situations where you want to stay with Array methods.

  • No answer directly attends to the question where it was asked also to put this in a function (As some answers are also mixing strings with arrays of strings, this is not completely unimportant).

  • 接受的答案需要 Linq,它是完全惯用的 C#,但它并非没有成本,并且在 C# 2.0 或更低版本中不可用。当涉及数组时,性能可能很重要,因此在某些情况下您希望使用 Array 方法。

  • 没有答案直接涉及还要求将其放入函数的问题(因为有些答案也将字符串与字符串数组混合,这并非完全不重要)。

Array.Exists() is a C#/.NET 2.0 method and needs no Linq. Searching in arrays is O(n). For even faster access use HashSet or similar collections.

Array.Exists() 是一种 C#/.NET 2.0 方法,不需要 Linq。在数组中搜索是 O(n)。为了更快地访问,请使用 HashSet 或类似的集合。

Since .NET 3.5 there also exists a generic method Array<T>.Exists():

从 .NET 3.5 开始,还存在一个通用方法Array<T>.Exists()

public void PrinterSetup(string[] printer)
{
   if (Array.Exists(printer, x => x == "jupiter"))
   {
      Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
   }
}

You could write an own extension method (C# 3.0 and above) to add the syntactic sugar to get the same ".Contains" for strings for all arrays without including Linq:

您可以编写自己的扩展方法(C# 3.0 及更高版本)来添加语法糖,以便在不包括 Linq 的情况下为所有数组的字符串获得相同的“.Contains”:

// Using the generic extension method below as requested.
public void PrinterSetup(string[] printer)
{
   if (printer.Contains("jupiter"))
   {
      Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
   }
}

public static bool Contains<T>(this T[] thisArray, T searchElement)
{
   // If you want this to find "null" values, you could change the code here
   return Array.Exists<T>(thisArray, x => x.Equals(searchElement));
}

In this case this Contains()method is used and not the one of Linq.

在这种情况下,使用此Contains()方法而不是 Linq 方法。

The elsewhere mentioned .Contains methods refer to List<T>.Contains(since C# 2.0) or ArrayList.Contains(since C# 1.1), but not to arrays itself directly.

其他地方提到的 .Contains 方法是指List<T>.Contains(自 C# 2.0 起)或ArrayList.Contains(自 C# 1.1 起),但不直接指代数组本身。