Reputation: 531
I have a table like
------------------ StudentId Name Subject Description 1 ABC CA Descr CA 2 ABC FM Descr FM 3 ABC MJ Descr MJ 4 ABC DM Descr DM ------------------
I have converted the data table to anonymous objects first
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;}
}
I need to convert it to student object
Upvotes: 2
Views: 896
Reputation: 35780
Try this. This is not for DB but you will correct easily:
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();
}
}
Upvotes: 2