Check if a value is in an array (C#)
Add necessary namespace
using System.Linq;
Then you can use linq Contains()
method
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains("jupiter"))
{
Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
}
How to check if an array contains a value stored in a variable
If you want to see if a value is in the array, use Contains
function. If you want to check whether arrays are equal use StructuralComparisons.StructuralEqualityComparer
. (https://learn.microsoft.com/en-us/dotnet/api/system.collections.structuralcomparisons.structuralequalitycomparer?view=netframework-4.7.2)
Code
static void Main(string[] args)
{
int compValue = 5;
int[] values0 = { 1, 2, 5, 7, 8 };
void ContainsValue(int[] array, int valueToTest)
{
bool isContained = array.Contains(valueToTest);
if (isContained)
Console.WriteLine($"{valueToTest} is in array");
else
Console.WriteLine($"{valueToTest} is not in array");
}
void CompareArrays(int[] array, int[] arrayToTest)
{
var comparer = StructuralComparisons.StructuralEqualityComparer ;
var areEqual = comparer.Equals(array, arrayToTest);
Console.WriteLine("-------------");
if (areEqual)
{
Console.WriteLine("Arrays are equal");
}
else
{
Console.WriteLine("Arrays are not equal");
}
}
ContainsValue(values0, compValue);
int[] compArray1 = { 1, 2, 5, 7, 8 };
CompareArrays(values0, compArray1);
int[] compArray2 = { 1, 2, 5, 15, 8 };
CompareArrays(values0, compArray2);
CompareArrays(compArray2, values0);
}
And the output:
5 is in array
-------------
Arrays are equal
-------------
Arrays are not equal
-------------
Arrays are not equal
Checking if a string array contains a value, and if so, getting its position
You could use the Array.IndexOf method:
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos > -1)
{
// the array contains the string and the pos variable
// will have its position in the array
}
Using C# to check if string contains a string in string array
Here is how you can do it:
string stringToCheck = "text1";
string[] stringArray = { "text1", "testtest", "test1test2", "test2text1" };
foreach (string x in stringArray)
{
if (stringToCheck.Contains(x))
{
// Process...
}
}
Maybe you are looking for a better solution... Refer to Anton Gogolev's answer which makes use of LINQ.
How do I check if value exists in array
Try
if (!func.contains(operation))
{
throw new Exception("");
}
Entering elements into an array and checking to see if the element already exists
Use .Any()
in System.Linq
. Also, you don't need to continuously grab user input in your loop:
using System;
using System.Linq;
public class Program
{
// Main method begins execution of C# application
public static void Main(string[] args)
{
int[] array = new int[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
// Get user input and convert to integer:
int input = Convert.ToInt32(Console.ReadLine());
// Check if given input is already in the array:
if (! array.Any(number => number == input))
{
array[i] = input;
Console.WriteLine("new\n");
}
else
{
Console.WriteLine("exists\n");
}
}
// Print the contents of array separated by ','
Console.WriteLine(string.Join(", ", array));
Console.ReadKey();
}
}
Edit: Another variant if you want the user to fill the array completely:
using System;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
// Btw, if this is not an array of nullables,
// we will not be able to insert a zero later, as
// we will treat them as duplicates.
int?[] array = new int?[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
int input = 0;
bool duplicateAttempt = false;
do {
// Get and convert the input.
input = Convert.ToInt32(Console.ReadLine());
// See if this number is already in.
duplicateAttempt = array.Contains(input);
// Report if we attempt to insert a duplicate.
if (duplicateAttempt) Console.WriteLine("exists");
}
while (duplicateAttempt); // Keep asking while we don't get a unique number.
array[i] = input; // Store the number
Console.WriteLine("new");
}
// Print the contents of array separated by ','
Console.WriteLine(string.Join(", ", array));
Console.ReadKey();
}
}
Conditional to check if array is equal to a particular value
You're comparing arrays, ==
in this case compares references and not values. If you want to compare the arrays' content, you could use SequenceEqual
:
hobbies.SequenceEqual(new string[0])
check if an array contains values of another array
Simple thing you missed, Take a look into the collection, All Items in the first list are larger than that of second, so the contains will return false. So you have to check for second item in first like the following:
Here is your modified code with result:
var result1 = list1.Where(x => list2.Any(y => x.Contains(y))).ToList();
var result2 = list2.Where(x => list1.Any(y => y.Contains(x))).ToList();
How can I check wether an array contains any item or is completely empty?
int[] a = new int[13]; // [0,0,0,0,0,0,0,0,0,0,0,0,0]
allocates a array with 13 items. The value of each item is 0
or default(int)
.
So you have to check
bool isEmpty = a.All(x => x == default(int));
If 0
is a valid value within your array, you should use nullable type:
int?[] a = new int?[13]; // [null,null,null,null,null,null,null,null,null,null,null,null,null]
bool isEmpty = a.All(x => !x.HasValue);
Related Topics
How to Do Template Specialization in C#
Escape Command Line Arguments in C#
Does Parallel.Foreach Limit the Number of Active Threads
Best Way in .Net to Manage Queue of Tasks on a Separate (Single) Thread
.Net: Determine the Type of "This" Class in Its Static Method
How to Mock Non Virtual Methods
Returning Only Part of Match from Regular Expression
Windows Forms Splash Screen - Show a Form While Loading Main Form
Strip the Byte Order Mark from String in C#
ASP.NET Core MVC:How to Get Raw JSON Bound to a String Without a Type
Service Hangs Up at Waitforexit After Calling Batch File
How to Kill a Thread Instantly in C#
Reading Excel File Using Oledb Data Provider
How to Stop Backgroundworker Correctly