0

i have two string array

string[] oldname = ["arun","jack","tom"];
string[] newname = ["jack","hardy","arun"];

here i want compare these two string arrays to get these distinct values separately like :

oldname = ["tom"];
newname = ["hardy"];

how to achieve these ...

3
  • Do you have to use arrays? Can you use List? Commented Feb 14, 2017 at 6:08
  • Does both array comprises of same size? Commented Feb 14, 2017 at 6:09
  • But your result doesn't show "distinct" values... If you ask distinct, the olname and newname must be printed as-is because they are "Distinct" Commented Feb 14, 2017 at 6:12

4 Answers 4

3
string[] oldNameDistinct = oldname.Where(s => !newname.Contains(s)).ToArray();
string[] newNameDistinct = newname.Where(s => !oldname.Contains(s)).ToArray();
Sign up to request clarification or add additional context in comments.

Comments

1

Let the two arrays were defined like the following:

 string[] oldname = new[] { "arun", "jack", "tom" };
 string[] newname = new string[] { "jack", "hardy", "arun" };

Then you can use the Extension method .Except to achieve the result that you are looking for. Consider the following code and the working example

 var distinctInOld = oldname.Except(newname);
 var distinctInNew = newname.Except(oldname);

2 Comments

this works but I believe it leaves a gap. What if there are multiples?
@MichaelBedford: Sorry I don't get you, what would be the changes in the input? could you please try with the Working example that i have added with my answer?
1

Try this :

    string[] oldname = new string[] { "arun", "jack", "tom" };
    string[] newname = new string[] { "jack", "hardy", "arun" };

    List<string> distinctoldname = new List<string>();
    List<string> distinctnewname = new List<string>();

    foreach (string txt in oldname)
    {
       if (Array.IndexOf(newname, txt) == -1)
         distinctoldname.Add(txt);
     }

     foreach (string txt in newname)
     {
        if (Array.IndexOf(oldname, txt) == -1)
          distinctnewname.Add(txt);
     }


   //here you can get both the arrays separately

Hope this help :)

Comments

0
string[] oldname = new []{"arun","jack","tom"};
string[] newname = new []{"jack","hardy","arun"};

// use linq to loop through through each list and return values not included in the other list.
var distinctOldName = oldname.Where(o => newname.All(n => n != o));
var distinctNewName = newname.Where(n => oldname.All(o => o != n));

distinctOldName.Dump(); // result is tom
distinctNewName.Dump(); // result is hardy

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.