获取数组linq中的多个字段

时间:2014-04-14 08:43:16

标签: c# sql linq

在我的应用程序中,用户可以拥有多个位置。我想在下拉列表中显示用户的所有位置。我创建了一个包含两个字段UserIDLocations的模型。位置是字符串数组。我想要一个Linq查询来获取UserID及其Locations。 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

4 个答案:

答案 0 :(得分: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()
});

答案 1 :(得分:0)

您可以使用.SelectMany()来实现此类输出:

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

答案 2 :(得分: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()之前执行,以便在数据库中完成过滤。

答案 3 :(得分:0)

试试这个:

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