2012-02-16 86 views
1

想LINQ的結果分配給一個多維數組和下面的是我的代碼,任何一個可以告訴我什麼,我做錯了。我如何LINQ結果分配給多維數組

var query = (from b in db.FourBodyImages 
      where b.Status == true 
      orderby b.CreaedDate descending 
      select new { b.BodyImage, b.Description, b.HeaderName } 
      ).Take(4).ToArray(); 

if(query.Count()>0) 
{ 
    string[,,] x = new string[4, 4,4]; 
    x[,,] = query; 

    for (int i = 0; i < query.Length; i++) 
    { 

     if (i == 0) 
     { 
      imgBody1.ImageUrl = "FourBodyImages/" + x[0,0,0].ToString(); 
     } 
     if (i == 1) 
     { 
      imgBody2.ImageUrl = "FourBodyImages/" + x[1,1,1].ToString(); 
     } 
     if (i == 2) 
     { 
      imgBody3.ImageUrl = "FourBodyImages/" + x[2,2,2].ToString(); 
     } 
     if (i == 3) 
     { 
      imgBody4.ImageUrl = "FourBodyImages/" + x[3,3,3].ToString(); 
     } 
    } 
} 
+0

我不認爲多維數組意味着你認爲它手段。 :)爲什麼你需要它是多維的?一個簡單的匿名對象數組可以做得很好。 – SWeko 2012-02-16 08:53:12

+0

數組'x [4,4,4]'有64個元素,而不是4個元素。你確定你需要3D陣列嗎? – dasblinkenlight 2012-02-16 08:56:29

+0

沒有我不需要一個三維陣列,讓我糾正我的問題 – Tan 2012-02-16 09:00:34

回答

0

如果你只是需要從數據庫中獲取4個對象,然後用它們來填充4張圖片,所有你需要做的是:

//this generates an array of (up to 4) objects of an anonymous type 
var query = (from b in db.FourBodyImages 
        where b.Status == true 
        orderby b.CreaedDate descending 
        select new { b.BodyImage, b.Description, b.HeaderName } 
        ).Take(4).ToArray(); 

//no need for count, we can use the array's length 
if (query.Length < 4) 
{ 
    //i have no idea about your requirements, 
    //but if we have less than 4 images - panic 
    throw new InvalidOperationException() 
} 

//no need for the "for-if", that's an anti-patern 
imgBody1.ImageUrl = "FourBodyImages/" + query[0].BodyImage; 
imgBody2.ImageUrl = "FourBodyImages/" + query[1].BodyImage; 
imgBody3.ImageUrl = "FourBodyImages/" + query[2].BodyImage; 
imgBody4.ImageUrl = "FourBodyImages/" + query[3].BodyImage; 
+0

謝謝你的建議 – Tan 2012-02-16 09:21:19

0

目前尚不清楚爲什麼要開始使用三維數組。你只取4個值......這是爲什麼不只是一個一維數組

var query = (from b in db.FourBodyImages 
      where b.Status == true 
      orderby b.CreaedDate descending 
      select new { b.BodyImage, b.Description, b.HeaderName } 
      ).Take(4).ToArray(); 

var bodies = new[] { imgBody1, imgBody2, imgBody3, imgBody4 }; 
for (int i = 0; i < query.Length; i++) 
{ 
    // Or whichever property you're interested in... 
    bodies[i].ImageUrl = "FourBodyImages/" + query[i].BodyImage; 
} 

如果這沒有幫助,請給我們更多關於您實際嘗試實現的內容的想法。爲什麼你的查詢返回三個屬性,例如,你想如何使用它們?

+0

怎麼樣b.description和b.headername如果他們被分配到不同的標籤 – Tan 2012-02-16 09:06:11

+0

@Tan:那麼這是很難給出示例代碼沒有什麼你任何線索正在努力去做。如果你能澄清你想達到的目標,我們可能會提供更多幫助。請閱讀http://tinyurl.com/so-hints – 2012-02-16 09:07:23

+0

我的查詢結果返回四行數據,我想分配給4個不同的標籤,圖片 – Tan 2012-02-16 09:17:18