Check all string in comma separated string exist in other using C# and VB.Net in ASP.Net

Last Reply 2 months ago By manvendra45

Posted 2 months ago

How to check all value with comma-separated exist in other parent comma separated in  c#

Suppose we have two string with comma-separated

for example  

string ParentString ="AAA,BBB,CCC";

String childstring ="BBB,CCC"

it must return true because all child string matched in parentstring

second example  

string ParentString ="AAA,BBB,CCC";

String childstring ="AA,CCC"

In this case, it must return false, because "AA" does not match any words which are comma-separated in ParentString 

Please help me, anyone, I had tried with Split and Contain function, but fail.

Posted 2 months ago Modified on 2 months ago

Hi manvendra45,

Refer below sample code.

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string parentString = "AAA,BBB,CCC";
        string[] parentarray = parentString.Split(',');
        string childstring = "AAA,AA,CCC";
        string[] childarray = childstring.Split(',');
        string notmatchvalue = "";
        foreach (var child in childarray)
        {
            Boolean checkExists = Array.Exists(parentarray, x => x == child);
            if (checkExists == false)
            {
                notmatchvalue = child;
                break;
            }
        }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim parentString As String = "AAA,BBB,CCC"
        Dim parentarray As String() = parentString.Split(","c)
        Dim childstring As String = "AAA,AA,CCC"
        Dim childarray As String() = childstring.Split(","c)
        Dim notmatchvalue As String = ""
        For Each child In childarray
            Dim checkExists As Boolean = Array.Exists(parentarray, Function(x) x = child)
            If checkExists = False Then
                notmatchvalue = child
                Exit For
            End If
        Next
    End If
End Sub

 


Posted 2 months ago Modified on 2 months ago

Here is anwser using Array 

string parentString = "AAA,BBB,CCC";
String[] parentarray=parentString.Split(',') ;//fill string as element in Array
string childstring = "AAA,AA,CCC";
childstring =childstring.split(',');
string notmatchvalue="";  
foreach (var child in childstring )
{
    Boolean checkExists = Array.Exists(parentarray, x => x ==child );
    if(checkExists ==false)
    {
        notmatchvalue=child //  do whatever want 
        break ;// it will break the foreach loop once get false and it will show this value is not matched with parentarray element 
    }
}

in this case "AA" will retrun false becuase it will not match to any array element.