我的SQL Server数据库中有一个State
和一个Cities
表(如下面的屏幕快照所示)。在我的C#Winforms项目中,我试图通过使用LINQ查询来生成州和每个州的城市数,但是它不能按我的意愿工作。
这是我的代码:
var states = (from u in db.States
join c in db.City on u.StateId equals c.StateId
group u by u.City into g
select new
{
StateId= u.StateId,
State Name = u.StateName, // Maybe g.Key here ??
Total Cities = g.Count // and here I am not sure
}).ToList();
dgvStates.DataSource = states;
答案 0 :(得分:2)
尝试这个:
var states = from u in db.States
join c in db.City on u.StateId equals c.StateId
group u by u.StateName into g
select new
{
StateName = g.Key,
TotalCities = g.Count()
};
请参见示例https://dotnetfiddle.net/1bqhTM
上面代码的结果
答案 1 :(得分:0)
这段代码可以工作:
public void LoadStates()
{
try
{
TESTEntities db = new TESTEntities();
// cmbProvince.Text = "";
var states = (from u in db.States
select new
{
u.StateId,
u.StateName,
u.Cityies.Count
}).ToList();
dgvStates.DataSource = states;
dgvStates.Columns[0].Visible = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}