2014-04-14 15 views
0

在我的應用程序中,用戶可以有多個位置。我想在下拉菜單中顯示用戶的所有位置。我創建了一個有兩個字段UserIDLocations的模型。位置是字符串數組。我想要一個Linq查詢來獲得UserID和他們的Locations。 Linq有可能嗎?獲取數組中的多個字段linq

public partial class ModelLocation 
{ 
    public int UserID { get; set; }  
    public string[] Locations{ get; set; } 
} 

在我的數據庫中的記錄都喜歡

UserID Location 
1   A 
1   B 
2   A 
3   B 
3   C 
3   D 
+0

在哪裏存儲您的源數據? –

回答

0
var models = db.Locations.GroupBy(l => l.UserId) 
.Select(l => new ModelLocation() 
{ 
    UserID = l.Key, 
    Locations = l.Select(l => l.Location).ToArray() 
}); 

根據您所使用的LINQ引擎(linq-to-sql,linq-to-entities)查詢會得到非常差的性能並導致多個查詢被髮送到數據庫。解決該問題的一種方法是首先從數據庫中檢索數據,然後在內存中執行分組,然後調用AsEnumerable()

var models = db.Locations.AsEnumerable().GroupBy(l => l.UserId) 
.Select(l => new ModelLocation() 
{ 
    UserID = l.Key, 
    Locations = l.Select(l => l.Location).ToArray() 
}); 

如果你想要做Where()任何過濾你應該做的之前調用AsEnumerable()獲得在DB進行過濾。

+0

偉大的解決方案;) –

+0

謝謝安德斯,我怎樣才能使用它加入?我在這裏只寫了兩個字段。實際上在我的模型中有九個字段。這些來自不同的表格。 –

+0

如果您已正確設置外鍵/關係,則可以使用導航屬性:http://coding.abel.nu/2012/06/dont-use-linqs-join-navigate/ –

0
// these are the raw db objects 
List<Record> records = new List<Record>(); 

var modelLocations = records.GroupBy(i => i.UserID).Select(g => new ModelLocation { 
    UserID = g.Key, 
    Locations = g.Select(j => j.Location).ToArray() 
}); 
+0

這不會創建一個'ModelLocation'對象。 –

+0

你是對的,我只是想改變我的答案,謝謝。 – sjkm

0

您可以使用.SelectMany()達到這樣的輸出:

var locations = modelLocations.SelectMany(x => x.Select(location => new { x.UserID, location })); 
0

試試這個:

var query = db.UserLocations 
      .GroupBy(l => l.UserID) 
      .Select(g => 
        new ModelLocation 
          { 
           UserID = g.Key, 
           Locations = g.Select(l => l.Location).ToArray() 
          }); 
相關問題