我试图按用户类型对所有用户进行分组将它们添加到列表中:
代码:
public string[] GroupByUserType()
{
using (DataBase db = new DataBase ())
{
var query = from e in db.Users
group db.Users by e.UserType;
string[] groups;
List<string> groupsByUserType = new List<string>();
foreach (var name in query)
{
foreach (var item in name)
{
groupsByUserType.Add(item);<--- error here
}
}
groups = groupsByUserType.ToArray();
return groups;
}
}
我得到:
错误1最佳重载方法匹配 &#39; System.Collections.Generic.List.Add(字符串)&#39;有一些无效的 参数C:\ Users \ Dev4 \ Documents \ Visual Studio 2008 \ Projects \ Linq \ SqlQuery \ QueryOnName.cs 27 25 SqlQuery
和
错误2参数&#39; 1&#39;:无法转换 &#39; System.Data.Linq.Table&#39;至 &#39;串&#39; C:\ Users \ Dev4 \ Documents \ Visual Studio 2008 \ Projects \ Linq \ SqlQuery \ QueryOnName.cs 27 46 SqlQuery
答案 0 :(得分:1)
问题是您的linq查询返回System.Data.Linq.Table
列表,尝试访问名称属性,如下所示:
public string[] GroupByUserType()
{
using (DataBase db = new DataBase ())
{
var query = from e in db.Users
group db.Users by e.UserType;
string[] groups;
List<string> groupsByUserType = new List<string>();
foreach (var name in query)
{
foreach (var item in name["name"])
{
groupsByUserType.Add(item);<--- error here
}
}
groups = groupsByUserType.ToArray();
return groups;
}
}
答案 1 :(得分:0)
将名称转换为String(),然后在制作字符串列表
时groupsByUserType.Add(item.Name);
希望这会有所帮助。