-6

I tried googling for the answer but at no avail. I'm new to coding in general, c# in particular and I'm trying to get head of the game by practicing.

So, what I am trying to do is to check if an array contains / has the same value that is stored in a variable previously declared. If it has, the code will do something, if it hasn't, the code will do something else altogether. What's the easiest way to accomplish what I want to do?

Thank you very much.

4

2 回答 2

0

怎么样(注意,我是通过电话来的)

var someVar =1;
var myArray = new [] {1, 2, 3};
bool doesItContain = myArray.Contains(someBar);

如果您在输入 后按下了点myArray,那么 Contains 将是建议之一。

您可以直接在if语句中使用,而不是盯着布尔变量中的结果。

于 2018-09-30T20:58:08.967 回答
0

如果要查看某个值是否在数组中,请使用Contains函数。如果要检查数组是否相等,请使用StructuralComparisons.StructuralEqualityComparer. (https://docs.microsoft.com/en-us/dotnet/api/system.collections.structuralcomparisons.structuralequalitycomparer?view=netframework-4.7.2

代码

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

和输出:

5 is in array
-------------
Arrays are equal
-------------
Arrays are not equal
-------------
Arrays are not equal
于 2018-09-30T21:20:46.890 回答