Get the value by a comparison between C#Arrays

Asked

Viewed 1,432 times

1

Well, I got two arrays:

first

string[] pastasSistema = new string[]
         {
                "Content",
                "DataRv",
                "My Skype Received Files",
                "RootTools",
                "shared_dynco",
                "shared_httpfe"
         };

2nd

string[] diretorios= new string[]
     {
            "Content",
            "DataRv",
            "My Skype Received Files",
            "Diferente",
            "RootTools",
            "shared_dynco",
            "shared_httpfe"
     };

Where I have the briefcase Diferente. What I want to do is compare these two arrays, and get the content that is different. In case I want to have the value DIFFERENT from within the Array diretorios

2 answers

3


You can use the Except of Linq, thus

string[] diff = diretorios.Except(pastasSistema).ToArray();

Realize that the Except only takes items from the first array that are not in the second, exactly as you ask

In case I want to have the value DIFFERENT from inside the Array directories

2

A more trivial method would be to go through both arrays:

List<string> diferentes = new List<string>();
for (int i = 0; i < diretorios.Length; j++) {
    bool existe = false

    for (int j = 0; j < pastasSistema.Length && !existe; j++) {
        if(diretorios[i].Equals(pastaSistema[j])) existe = true
    }
    if(!existe) diferentes.Add(diretorios[i]);

}

But the language contains simpler methods that do this for you. Look at jbueno’s answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.