[英]Compare and complete two arrays
我需要將數組與數組模型進行比較,並完成結構,例如以下示例:
array = [0,1,2,3,4]
model = [0,0,0,0,0,0,0]
result = [0,1,2,3,4,0,0]
該模型無法更改,它是一個參考數組。
關於實現此目標的最佳方法有什么想法?
將短的副本復制到長的副本中:
int[] array = { 0, 1, 2, 3, 4 };
int[] model = { 0, 0, 0, 0, 0, 0, 0, };
int[] result = model;
array.CopyTo(result, 0);
Console.WriteLine(String.Join(" ", result));
如果最好的方法如您在評論中所寫的最快,那么這里是一個比較:
Stopwatch st = new Stopwatch();
int[] array = new int[10000];
int[] model = new int[10200];
st.Start();
var asdf = array.Concat(model.Skip(array.Length)).ToArray();
st.Stop();
Console.WriteLine("Concat: " + st.ElapsedMilliseconds);
int[] arraya = new int[10000];
int[] modela = new int[10200];
st.Restart();
int[] result = modela;
arraya.CopyTo(result, 0);
st.Stop();
Console.WriteLine("Copy: " + st.ElapsedMilliseconds);
如果您事先知道數組長度,則可以執行此操作...
int[] array = { 0, 1, 2, 3, 4 };
int[] model = { 0, 0, 0, 0, 0, 0, 0, };
Array.Copy(array, model, array.Length);
如果沒有的話,你可以這樣...
int[] model = { 0, 1, 2, 3, 4 };
var array = new int[7];
var shorter = array.Length < model.Length ? array : model;
var longer = array.Length >= model.Length ? array : model;
Array.Copy(shorter, longer, shorter.Length);
...最快速度而不會改變原稿...
int[] array = { 0, 1, 2, 3, 4 };
int[] model = { 4,5,6,7,8,9,1, };
var x = array.Length < model.Length ?
new { s = array, l = model, sl = array.Length, ll = model.Length } :
new { s = model, l = array, sl = model.Length, ll = array.Length };
var result = new int[x.ll];
Array.Copy(x.s, result, x.sl);
Array.Copy(x.l, x.sl, result, x.sl, x.ll - x.sl);
這是我的版本...可能比LINQ快一點。 我的假設是您要替換具有更大數字的數組,但我可能是錯的。
var array = new[]{0,1,2,3,4};
var model = new[]{0,0,0,0,0,0,0};
for(int i = 0; i < array.Length; i++)
{
if(array[i] > model[i])
{
model[i] = array[i];
}
}
如果沒有,您可以簡單地執行Array.Copy
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.