Tuesday, 14 May 2013

.Net Tips: Check that particular word or string part contains in string array using LINQ "Any" method With C#.Net and VB.Net Examples

There are situations were we have string array which contains many value and we want to check that particular word or string part exist in all values.
We want to avoid iteration of array at that time we can use LINQ's "Any" method. Using one line code we can check.

Here is example for this :
In this example we take on string array "ProductArray" and insert some values. Now we want to check that "er" word is contain any values of this array or not using "Contains" method. You can check output below.

C#. Net Example :
        string[] ProductArray = { "CPU", "Computer", "DVD", ".Net" };

        bool isExist = ProductArray.Any(o => o.Contains("er"));

        Response.Write("There is a word in the list that contains 'er': <b>" + isExist + "</b>");

VB.Net Examples :
        Dim ProductArray As String() = {"CPU", "Computer", "DVD", ".Net"}

        Dim isExist As Boolean = ProductArray.Any(Function(o) o.Contains("er"))

        Response.Write("There is a word in the list that contains 'er': <b>" & isExist & "</b>")

Output :

1 comment: