2013-02-13 104 views
-2

我試圖將所有用戶按用戶類型將它們添加到列表:
代碼:查詢打印

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(string)'有一些無效的參數C:\ Users \ Dev4 \ Documents \ Visual Studio 2008 \ Projects \ Linq \ SqlQuery \ QueryOnName.cs 27 25 SqlQuery

錯誤2參數 '1':不能轉換從 'System.Data.Linq.Table' 至 '字串' C:\用戶\ DEV4 \文件\的Visual Studio 2008 \項目\ LINQ的\ SqlQuery類\ QueryOnName.cs 27 46類SqlQuery

+1

你分析你的類型變量的調試器? – 2013-02-13 17:00:06

+0

變量的_type(s)_是什麼? – Brian 2013-02-13 17:00:52

回答

0

轉換名稱的toString(),然後當你正在字符串列表

groupsByUserType.Add(item.Name); 

希望這有助於。

1

的問題是你的LINQ查詢返回的System.Data.Linq.Table列表,嘗試訪問name屬性是這樣的:

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; 
    } 
}