开发者

Group content by dynamic database field

Is there a way to group content within a Repeater with a dynamic heading?

For example, I have the following in a database:

  • Tuesday - math
  • Tuesday - science
  • Friday - history
  • Friday - art

I want it to be displayed in output on a web page as:

I want the items to be grouped by day; however, I do not want to create a new database connection for each day of the week, and I don't want to hard code groups. Is there a way to group content by a database field?

Thank you in advance for your help.


You can use LINQ to modify the datasource that you're binding to the repeater.

This should work:

//original datasource from database
DataTable table = new DataTable();

//modify the datasource using LINQ
var results = from row in table.AsEnumerable()
              group row by row.Field<string>("Day") into days
              select new
              {
                  Day = days.Key,
                  Class = String.Join(", ", days.Select(t => t.Field<string>("Class")).ToArray())
              };

//bind the repeater to the modified datasource
Repeater1.DataSource = results;

EDIT

Here are some tutorials to get you started using LINQ:

  • http://msdn.microsoft.com/en-us/vcsharp/aa336746
  • http://aktripathi.wordpress.com/2009/01/08/linq-for-beginners/
  • http://www.programmersheaven.com/2/CSharp3-4
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜