Fun With Arrays in C#

As a webdev, I like using arrays to hold things to look them up later. I thought I’d be clever and store the menu choices in an array for the if block, and check if an item is in the array to decide what to do.

In regular ol’ vanilla Javascript, such a lookup might look like

var colors= ["Red", "Blue", "Green"];

console.log(colors.includes("Red"));

console.log(colors.includes("Yellow"));

and return

true
false

Easy!

Not so much in C#…
10 minutes into a rabbit hole later - there isn’t a simple lookup for an array element without looping over the contents - UNLESS you add using System.Linq; to the top of the file.

Linq is a library made for querying data sources and is probably overkill for array lookups. Using Linq did allow me to do choices.Contains, where choices is the name of my array.

Here is what I came up with:

Maybe as I become better at C# I’ll find a more standardized way - keep learning everyone!

1 Like

Another approach could be to just use the builtin array function that would return a valid index or -1 to look for the item . This avoids the need for adding in Linq just for this.

int index = Array.IndexOf(choices, input);
// index will be -1 if choices does not contain input

1 Like

Thanks for the tip - that totally worked - not sure how I missed that :slight_smile:

If anyone is wondering, I changed the code to

if(Array.IndexOf(choices, input) > -1) {

Privacy & Terms