我想知道是否有一种比较两个整数数组的简单方法,并按顺序在第一个数组源中添加缺少的元素。
例子代码:
//Two list [source , compare ]
public int[] ListSource = new int[]{ 4,8,12,20,24,32 } ;
public int[] ListToCompare = new int[] { 3, 8, 16, 16, 20, 24, 28, 32,36 };
//If size of array is different , we resize the source
if(ListSource.Length != ListToCompare.Length)
{
Array.Resize(ref ListSource, ListToCompare.Length);
}
// Compare and update
for(int a = 0 ; a < ListToCompare.Length;a++)
{
if(ListSource[a] != ListToCompare[a])
{
// .... How can i do it
}
}
//And finally my Listsource is complete merge with the listToCompare and in good order
//ListSource = { 3, 4, 8, 12, 16, 16, 20, 24, 28, 32 };
非常感谢: - )
答案 0 :(得分:2)
试试这个:
ListSource = ListToCompare.Where(x=>!ListSource.Contains(x))
.Concat(ListSource).OrderBy(x => x).ToArray();
点击此处查看结果:http://ideone.com/6CY4lp
它将保留示例结果中的双16
答案 1 :(得分:1)
//Here is a sample on how you can achieve this
static void Main(string[] args)
{
//Two list [source , compare ]
int[] ListSource = new int[]{ 4,8,12,20,24,32 } ;
int[] ListToCompare = new int[] { 3, 8, 16, 16, 20, 24, 28, 32,36 };
var res = ListToCompare.Except(ListSource);
var NewListSource = ListSource.ToList();
NewListSource.AddRange(res);
ListSource = NewListSource.OrderBy(x=>x).ToArray();
//And finally my Listsou
}
}
答案 2 :(得分:1)
var set = new HashSet<int>();
set.UnionWith(ListSource);
set.UnionWith(ListToCompare);
ListSource = set.OrderBy(x => x).ToArray();
答案 3 :(得分:1)
你可以试试这个:
var except = list2.Except(list1);
var result = list1.Union(except).OrderBy(x => x);
或短
var result = list1.Union(list2.Except(list1)).OrderBy(x => x);