2013-08-17 69 views
1

我想從表中只取兩列,並將它放在列表中,但不是放入二維數組字符串string[,]。我在做什麼:如何將數據庫結果轉換爲二維數組

string[,] array = _table.Where(x => x.IsDeleted == false) 
    .Select(y => new string[,] {{y.Name, y.Street}}); 

現在我不知道如何執行它。如果我做.ToArray()我會得到string[][,]。任何人都知道如何用LINQ解決它,而不使用循環?

+1

你不能得到'字符串[,]'作爲LINQ查詢的輸出。 – MarcinJuraszek

回答

1

沒有什麼在LINQ可以讓你創建多維數組。但是,您可以創建自己的擴展方法將返回TResult[,]

public static class Enumerable 
{ 
    public static TResult[,] ToRectangularArray<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult[]> selector) 
    { 
     // check if source is null 
     if (source == null) 
      throw new ArgumentNullException("source"); 

     // load all items from source and pass it through selector delegate 
     var items = source.Select(x => selector(x)).ToArray(); 

     // check if we have any items to insert into rectangular array 
     if (items.Length == 0) 
      return new TResult[0, 0]; 

     // create rectangular array 
     var width = items[0].Length; 
     var result = new TResult[items.Length, width]; 
     TResult[] item; 

     for (int i = 0; i < items.Length; i++) 
     { 
      item = items[i]; 

      // item has different width then first element 
      if (item.Length != width) 
       throw new ArgumentException("TResult[] returned by selector has to have the same length for all source collection items.", "selector"); 

      for (int j = 0; j < width; j++) 
       result[i, j] = item[j]; 
     } 

     return result; 
    } 
} 

但正如你所看到的,但它仍然得到所有結果成鋸齒狀排列TResult[][],然後再利用循環將其改寫成多維數組。

用例:

string[,] array = _table.Where(x => x.IsDeleted == false) 
         .ToRectangularArray(x => new string[] { x.Name, x.Street }); 
+0

這是爲什麼downvoted? (什麼是'==假'?) – Sayse

+0

@Sayse我不知道爲什麼這是downvoted,但我知道'==假'是問題的原始查詢的一部分,這就是爲什麼我沒有改變到'!IsDeleted'。 – MarcinJuraszek

2

string[,]不可能作爲LINQ查詢的輸出。

作爲替代你可以嘗試這樣的事: -

string[][] array = _table.Where(x => x.IsDeleted == false).Select(y => new[] {y.Name, y.Streete}).ToArray(); 

OR

var array =_table.Select(str=>str.Where(x => x.IsDeleted == false) 
     .Select(y => new[] {y.Name, y.Street}) 
     .ToArray()) 
    .ToArray(); 
+0

他希望'string [,]',而不是'string [] []' – MarcinJuraszek

+0

string [,]是一個多維數組,並且OP已經提到將它轉換成一個2D數組(如果我錯了,請糾正我) –

+0

他指出他想要'string [,]'。 'string [] []'是鋸齒形的字符串數組。 – MarcinJuraszek