日期:2014-05-20  浏览次数:20815 次

asp.net mvc3环境下,用linq实现主题栏目分层显示
asp.net mvc3环境下,用linq实现主题栏目分层显示
例有两个表了
a
id 主题 序列
1 第一 1
2 第二 2
3 第三 3

b
id 分主题 序列
1 小1 1
2 小2 1
3 小1 2
4 小2 2
5 小1 3

实现显示如下效果:

第一
  小1
  小2
第二
  小1
  小2
第三
  小1





------解决方案--------------------
可以使用分组联合

C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class ta
    {
        public int id { get; set; }
        public string 主题 { get; set; }
        public string 序列 { get; set; }
    }

    class tb
    {
        public int id { get; set; }
        public string 分主题 { get; set; }
        public string 序列 { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<ta> la = new List<ta>()
            {
                new ta() { id = 1, 主题 = "第一", 序列 = "1" },
                new ta() { id = 2, 主题 = "第二", 序列 = "2" },
                new ta() { id = 3, 主题 = "第三", 序列 = "3" }
            };
            List<tb> lb = new List<tb>()
            {
                new tb() { id = 1, 分主题 = "小1", 序列 = "1" },
                new tb() { id = 2, 分主题 = "小2", 序列 = "1" },
                new tb() { id = 3, 分主题 = "小1", 序列 = "2" },
                new tb() { id = 4, 分主题 = "小2", 序列 = "2" },
                new tb() { id = 5, 分主题 = "小1", 序列 = "3" }
            };
            var result = from a in la
                         join b in lb on a.序列 equals b.序列 into g
                         select new { a.主题, items = g };
            foreach (var item in result)
            {
                Console.WriteLine(item.主题);
                foreach (var sitem in item.items)
                    Console.WriteLine("\t" + sitem.分主题);
            }
        }        
    }
}