c# - How to check whether an element exists in an array

Array exists
The following asp.net c# example code demonstrate us how can we determine whether specified elements are exists in an array based on search criteria. .Net framework's Array Class Array.Exists<T>() method allow us to determine whether the specified array contains one or more elements that match the conditions defined by the specified predicate.

Array.Exists<T>() method type parameter is 't' which represent the type of the elements of the array. This method has two required parameters named 'array' and 'match'. The 'array' parameter represent the one-dimensional, zero-based index array to search. The 'match' parameter value represent the Predicate<T> that defines the conditions of the elements to search for.

Array.Exists() method return a Boolean value. It return 'true', if array contains value that match the condition; otherwise it return 'false'.

In this example code, we call the Array.Exists() method three times. First and second call, we check whether array contain an element with value 'skyblue' and 'green.' Third call, we search the array for elements whose value ends with character 'd'.

<%@ Page Language="C#" AutoEventWireup="true"%>  
<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
        string[] colors = new string[]

        Label1.Text = "colors array.........<br />";
        foreach (string s in colors)
            Label1.Text += s + "<br />";

        Boolean skyblueExists = Array.Exists(colors, x => x == "skyblue");
        Boolean greenExists = Array.Exists(colors, x => x == "green");
        Boolean colorEndEithd = Array.Exists(colors, x=> x.EndsWith("d"));

        Label1.Text += "<br />skyblue color exists in color array? " + skyblueExists.ToString();
        Label1.Text += "<br />green color exists in color array? " + greenExists.ToString();
        Label1.Text += "<br />any color end with 'd' exists in color array? " + colorEndEithd.ToString();
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - array exists</title>  
    <form id="form1" runat="server">  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - array exists
        <hr width="550" align="left" color="LightBlue" />    
        <br /><br />
            Text="test array exists"  
More c# examples