T-SQL2000和C#返回按ID分组的N条记录

时间:2018-05-31 17:49:59

标签: c# sql-server tsql

让我试着解释一下我想要实现的目标

请考虑以下信息:

public class RootObj
{
   public string id { get; set; }
   public List<string> infoList { get; set; }
}

我想只执行一个查询db函数,该函数返回给我一个 RootObj 的列表 像这样:

public List<RootObj> getContactListAddContacts()
{
   ... //get db stuff
   List<RootObj> list = new List<RootObj>();
   dr = cmd.ExecuteReader();
   while (dr.Read())
   {
      RootObj obj = new RootObj();
      obj.id = (int)dr["table1_id"];
      obj.infoList = ...;//NEED HELP HERE list of table2_id 
      list.add(obj);
   }
   return list;
}

并在SQL中考虑此表

+-----+-----------+-----------+
| id  | table1_id | table2_id |
+-----+-----------+-----------+
| 1   | 1         | a         |
+-----+-----------+-----------+
| 2   | 1         | b         |
+-----+-----------+-----------+
| 3   | 2         | c         |
+-----+-----------+-----------+
| 4   | 3         | c         |
+-----+-----------+-----------+
| 5   | 3         | d         |
+-----+-----------+-----------+

预期结果必须是以下结果:

list = [
          {
             id:1,
             infoList = {a, b}
          },
          {
             id:2,
             infoList = {c}
          },
          {
             id:3,
             infoList = {c,d}
          }
       ]

(像json一样,因为它很容易看到)

我的程序应如何实现这一目标?

到目前为止,无法想到

select table1_id, table2_id from table1_table2

但是我不知道如何将这个添加到我的对象中就像我想要的那样

提前致谢。

2 个答案:

答案 0 :(得分:0)

用字典试试linq:

        public Dictionary<int, List<string>> getContactListAddContacts()
        {
           //get db stuff
            SqlDataAdapter adapter = new SqlDataAdapter();
            DataTable dt = new DataTable();
            adapter.Fill(dt);

            return dt.AsEnumerable()
                .GroupBy(x => x.Field<int>("table1_id"), y => y.Field<string>("table2_id"))
                .ToDictionary(x => x.Key, y => y.ToList());
        }

答案 1 :(得分:0)

嗯..我可以用这种方法解决

while (dr.Read())
            {
                hasId = false;
                foreach(RootObj cat in list)
                {
                    if(cat.list_id == dr["table1_id"].ToString())
                    {
                        cat.external_ids.Add((string)dr["table2_id"]);
                        hasId = true;
                        break;
                    }
                }
                if (!hasId)
                {
                    RootObj cat = new RootObj(dr["table1_id"].ToString());
                    List<string> externalList = new List<string>();
                    externalList.Add((string)dr["table2_id"]);
                    cat.external_ids = externalList;
                    list.Add(cat);
                }
            }

非常感谢 jdweng 快速回复