2017-04-13 43 views
-1

考慮以下幾點:LINQ ToArray的()改變陣列長度

Dictionary<int,int> dict = new Dictionary<int,int>(); 
dict.Add(1, 3); 
dict.Add(3, 4); 

int [] a = new int [] { 1, 2, 3 }; 
int [] b = new int [a.Length]; 

Console.WriteLine("a:"); 
a.Dump(); //using linqpad here 

Console.WriteLine("b:"); 
b.Dump(); //using linqpad here 

b = dict.OrderByDescending(x => x.Value).Select(x => x.Key).ToArray(); 
Console.WriteLine("b after linq:"); 
b.Dump(); //using linqpad here 

成績

a: 1 2 3 

b: 0 0 0 

b after linq: 3 1 

我已經現有陣列a。我創建了一個長度相同的新陣列b。經過linq查詢後,ToArray()值被添加到新數組b,但長度發生變化。有沒有辦法保留原始數組長度,同時仍然將值添加到它?

期望的結果

b after linq: 3 1 0 
+0

你是**用'Dictionary <>'鍵重新賦值你的b數組,所以結果在任何方面都是正確的。 –

+0

您必須將'dict.OrderByDescending(x => x.Value).Select(x => x.Key).ToArray();'的結果賦值給另一個變量,然後將'Array.Copy'賦值給'b '從那裏。 – dcg

+0

ToArray()方法不會更改b的長度。它從兩個字典鍵創建一個新的數組。 'b ='賦值用新創建的數組替換舊的b數組。您可能想要循環新數組並將每個值分配給數組b中的相應索引。 –

回答

1

正如Sergey已發佈的那樣,您將使用Linq語句重新分配b的內容。如果你想以填補零的陣列的其餘部分到Linq的語句之後給定數量的使用:

Array.Resize(ref b, a.Length); 

這樣,你得到你想要的結果3 1 0

注意到,這一操作創建一個新的數組並用此數組替換現有變量b

+0

這確實需要什麼,謝謝。 – PixelPaul

2

這是一個賦值操作:

b = dict.OrderByDescending(x => x.Value).Select(x => x.Key).ToArray(); 

它取代參考陣列new int [a.Length],你必須在可變b新的參考用LINQ查詢創建陣列。賦值不會改變第一個數組中的值。

如果要通過與來自第二陣列的物品從第一陣列替換對應項「合併」兩個陣列,則可以創建自定義擴展方法(沒有默認LINQ擴展爲):

public static IEnumerable<T> MergeWith<T>(
    this IEnumerable<T> source, IEnumerable<T> replacement) 
{ 
    using (var sourceIterator = source.GetEnumerator()) 
    using (var replacementIterator = replacement.GetEnumerator()) 
    { 
     while (sourceIterator.MoveNext()) 
      yield return replacementIterator.MoveNext() 
       ? replacementIterator.Current 
       : sourceIterator.Current; 

     // you can remove this loop if you want to preserve source length 
     while (replacementIterator.MoveNext()) 
      yield return replacementIterator.Current; 
    } 
} 

用法:

b = b.MergeWith(dict.OrderByDescending(x => x.Value).Select(x => x.Key)).ToArray(); 

輸出:

b after linq: 3 1 0 
+1

謝謝,這是非常豐富的。 – PixelPaul

-1

你只加 「3」 和 「1」到你的字典。 如果您想要「3 1 0」作爲結果,您還需要在字典中添加一個「0」。