2017-02-14 34 views
0

我有兩個字符串數組如何在字符串數組中分別獲取不同的值?

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

在這裏,我想比較這兩個字符串數組分別獲得這些不同的值,如:

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

如何實現這些...

+0

你有使用數組?你能用List嗎? –

+0

這兩個數組是否包含相同的大小? –

+0

但你的結果並不顯示「獨特」的價值......如果你問清楚,olname和newname必須按原樣打印,因爲它們是「獨特」的 – A3006

回答

3
string[] oldNameDistinct = oldname.Where(s => !newname.Contains(s)).ToArray(); 
string[] newNameDistinct = newname.Where(s => !oldname.Contains(s)).ToArray(); 
1

讓兩個陣列定義如下:

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

然後,您可以使用擴展方法.Except來實現您正在查找的結果。請看下面的代碼和working example

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

這個工程,但我相信它會留下一個空白。如果有倍數呢? –

+0

@邁克爾貝德福德:對不起,我不明白你會怎樣改變輸入?你能否請用我的答案添加的工作例子來嘗試? –

1

試試這個:

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 

希望這有助於:)

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 
相關問題