将数据表转换为嵌套对象

时间:2015-01-31 13:36:34

标签: linq c#-4.0

我有一张像

这样的表格
 
------------------
StudentId Name Subject Description
1     ABC   CA     Descr CA  
2     ABC   FM     Descr FM
3     ABC   MJ     Descr MJ 
4     ABC   DM     Descr DM
------------------

我先将数据表转换为匿名对象

var studentPlain= from dr in tbl.AsEnumerable()
      select new{
      StudentId =Convert.ToInt32(dr["StudentId"]),
      Name=Convert.ToString(dr["Name"]),
      Subject =Convert.ToString(dr["Subject"]),
      Description = Convert.ToString(dr["Description"])
      } 

class subj
{
public string Subject {get;set;}
public string Description {get;set;}
}
class student
{
public int StudentId {get;set;}
public string Name {get;set;}
public List<subj> subjects{get;set;}
}

我需要将其转换为学生对象

1 个答案:

答案 0 :(得分:2)

试试这个。这不适用于数据库,但您可以轻松纠正:

public class dbStudent
{
    public int StudentId;
    public string Name;
    public string Subject;
    public string Description;
}

public class subject
{
    public string Subject;
    public string Description;
}

public class student
{
    public int StudentId;
    public string Name;
    public List<subject> subjects;
}

class Program
{
    static void Main(string[] args)
    {
        var dbStudebts = new List<dbStudent>();
        dbStudebts.Add(new dbStudent { StudentId = 1, Name = "Bob", Subject = "Math", Description = "High math" });
        dbStudebts.Add(new dbStudent { StudentId = 1, Name = "Bob", Subject = "Geography", Description = "Mountains" });
        dbStudebts.Add(new dbStudent { StudentId = 2, Name = "John", Subject = "Philosophy", Description = "Philosophy of life" });

        var result = (from o in dbStudebts
                      group o by new { o.StudentId, o.Name } into grouped
                      select new student()
                      {
                          StudentId = grouped.Key.StudentId,
                          Name = grouped.Key.Name,
                          subjects = grouped.Select(c => new subject()
                          {
                              Subject = c.Subject,
                              Description = c.Description
                          }).ToList()
                      }).ToList();
    }
}