.net - Join rows using C# Linq -
if there datatable called students
subjectid studentname ---------- ------------- 1 mary 1 john 1 sam 2 alaina 2 edward
how can below datatable result using linq:
subjectid studentname ---------- ------------- 1 mary, john, sam 2 alaina, edward
i tried achieving result using foreach loop crawling through each datarow 1 one came across major performance hit.
not linq trying hands on it. post answer once concrete appreciated in between.
sample working code without using linq not giving desired performance. below foreach loop taking around 15mins if datatable dt2 has around 3500 records.
datatable dtfiles = dt2.clone(); //logic filter out files keyword name filter. foreach (datarow row in dt2.rows) { string studentid = row.field<string>("studentid"); string filter = "studentid = '" + studentid + "'"; if(dtfiles.select(filter).count() == 0)//this means keyword new { datarow dr = dtfiles.newrow(); dr["studentname"] = row["studentname"]; dr["studentid"] = row["studentid"]; dtfiles.rows.add(dr); } else { dtfiles.select(filter).first<datarow>()["studentname"] += "," + row.field<string>("studentname");//rows[0] } }
get grouped data
var subjects = r in dtfiles.asenumerable() group r r.field<int>("subjectid") g select new { id = g.key, students = string.join(", ", g.select(r => r.field<string>("studentname")) };
then build datatable (if need it)
datatable dt = new datatable(); dt.columns.add("subjectid", typeof(int)); dt.columns.add("studentname", typeof(string)); // or can clone existing datatable: datatable dt = dtfiles.clone(); foreach(var subject in subjects) dt.add(subject.id, subject.students);
Comments
Post a Comment