查询要打印的组

本文关键字:打印 查询 | 更新日期: 2023-09-27 17:58:55

我正在尝试按用户类型对所有用户进行分组,将它们添加到列表中:
代码:

   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的最佳重载方法匹配"System.Collections.Generic.List.Add(字符串)"包含一些无效内容参数C:''Users''Dev4''Documents''Visual Studio2008''Projects''Linq''SqlQuery''QueryOnName.cs 27 25 SqlQuery

错误2参数"1":无法从转换"System.Data.Linq.Table"到'string'C:''Users''Dev4''Documents''Visual Studio2008''Projects''Linq''SqlQuery''QueryOnName.cs 27 46 SqlQuery

查询要打印的组

问题是您的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;
    }
}

将名称转换为字符串(),然后在制作字符串列表时

groupsByUserType.Add(item.Name);

希望这能有所帮助。