我有两个字符串数组
string[] oldname = ["arun","jack","tom"];
string[] newname = ["jack","hardy","arun"];
这里我想比较这两个字符串数组来分别得到这些不同的值,如:
oldname = ["tom"];
newname = ["hardy"];
如何实现这些......
答案 0 :(得分:3)
string[] oldNameDistinct = oldname.Where(s => !newname.Contains(s)).ToArray();
string[] newNameDistinct = newname.Where(s => !oldname.Contains(s)).ToArray();
答案 1 :(得分: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);
答案 2 :(得分: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
希望这有帮助:)
答案 3 :(得分: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