您好我有两个实体模型,表中的数据为:
Table Group
id name
1 NW
2 SW
3 NE
Second Table is
Location
id groupId count
1 1 34
2 2 5
3 2 90
4 1 33
5 1 23
我想写一个linq查询或在EF中使用上下文,以便我可以按每个groupId进行分组,以便结果为
groupdId 1
{count 34, 33, 23}
groupId 2
{count 90,5}
我试过以下
from e in DbContext.Set<Group>()
join a in DbContext.Set<locatin>() on e.Id equals a.groupId
Select new Test
{
groupId= e.groupdId
tables = new List<tbl>()
{
count= a.count;
}
}
public class Test
{
public int groupId {get; set;}
public IEnumerable<gbl> Tables {get; set;}
}
public class tbl
{
public int count {get; set;}
}
当我到达count=a.count
时写入查询,我得到intellisense错误无法解决。请让我知道如何更正我的查询,以便我得到groupId的标题然后只有计数数字的另一个数组。感谢。
答案 0 :(得分:1)
以下将适用于此案例:
var result =
groups.Join(locations,g=>g.id,l=>l.groupId,(g,l)=>new {l})
.GroupBy(x =>x.l.groupId,x=>x.l.count)
.Select(y=>new Test
{
groupId= y.Key,
tables = y.Select(n => new tbl{count = n})
});
以下是步骤:
groups
和locations
id
和groupid
GroupBy
结果并预测count
Select
,结果应为IEnumerable<Test>
以下是我完整的代码,我用来创建解决方案(使用LinqPad):
void Main()
{
var groups = Group.CreateList();
var locations = Location.CreateList();
var result =
groups.Join(locations,g=>g.id,l=>l.groupId,(g,l)=>new {l})
.GroupBy(x =>x.l.groupId,x=>x.l.count)
.Select(y=>new Test
{
groupId= y.Key,
tables = y.Select(n => new tbl{count = n})
});
result.Dump();
}
public class Group
{
public int id;
public string name;
public static List<Group> CreateList()
{
return new List<Group>
{
new Group
{
id = 1,
name = "NW"
},
new Group
{
id = 2,
name = "SW"
},
new Group
{
id = 3,
name = "NE"
}
};
}
}
public class Location
{
public int id;
public int groupId;
public int count;
public static List<Location> CreateList()
{
return new List<Location>
{
new Location
{
id = 1,
groupId = 1,
count = 34
},
new Location
{
id = 2,
groupId = 2,
count = 5
},
new Location
{
id = 3,
groupId = 2,
count = 90
},
new Location
{
id = 4,
groupId = 1,
count = 33
},
new Location
{
id = 5,
groupId = 1,
count = 23
}
};
}
}
public class Test
{
public int groupId {get; set;}
public IEnumerable<tbl> tables {get; set;}
}
public class tbl
{
public int count {get; set;}
}