简体   繁体   English

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

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

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?如何以 C# 可以识别的方式格式化if (printer == "jupiter")

Add necessary namespace添加必要的命名空间

using System.Linq;

Then you can use linq Contains() method然后你可以使用 linq Contains()方法

string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains("jupiter"))
{
    Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
}
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); // true
Console.WriteLine(b); // false
Console.WriteLine(c); // true
Console.WriteLine(d); // false

Add using System.Linq; using System.Linq; at the top of your file.在文件的顶部。 Then you can do:然后你可以这样做:

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

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

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"");
    }
}

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.接受的答案需要 Linq,它是完全惯用的 C#,但它并非没有成本,并且在 C# 2.0 或更低版本中不可用。 When an array is involved, performance may matter, so there are situations where you want to stay with Array methods.当涉及到数组时,性能可能很重要,因此在某些情况下您希望使用 Array 方法。

  • 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).没有答案直接涉及要求将其放入函数中的问题(由于某些答案还将字符串与字符串数组混合,这并非完全不重要)。

Array.Exists() is a C#/.NET 2.0 method and needs no Linq. Array.Exists() 是 C#/.NET 2.0 方法,不需要 Linq。 Searching in arrays is O(n).在数组中搜索是 O(n)。 For even faster access use HashSet or similar collections.为了更快地访问,请使用 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/similar ".Contains" as for strings for all arrays without including Linq:您可以编写自己的扩展方法(C# 3.0 及更高版本)来添加语法糖以获得与所有数组的字符串相同/相似的“.Contains”,而不包括 Linq:

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

public static bool ArrayContains<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 ArrayContains() method is used and not the Contains method of Linq.在这种情况下,这个ArrayContains()方法被使用,而不是 Linq 的 Contains 方法。

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 起),但不直接指数组本身。

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 string and you'll be fine.只需添加string ,你会没事的。

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" ) ) )
    {
        ...
    }

Consider using HashSet<T> Class for the sake of lookup performance:为了查找性能考虑使用HashSet<T>

This method is an O(1) operation.此方法是 O(1) 操作。

HashSet<T>.Contains Method (T), MSDN . 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");
        }
        // ...
    }
}

I searched now over 2h to find a nicely way how to find duplicates in a list and how to remove them .我现在搜索了超过 2 小时,以找到一种如何在列表中查找重复项以及如何删除它们的好方法。 Here is the simplest answer:这是最简单的答案:

//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 的新列表中删除!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM