首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

linq有关问题,同一个表多种查询返回一个结果集

2013-07-20 
linq问题,同一个表多种查询返回一个结果集有一个文章表,每篇文章表分属不同栏目,现要在首页显示每个栏目的

linq问题,同一个表多种查询返回一个结果集
有一个文章表,每篇文章表分属不同栏目,现要在首页显示每个栏目的最新的10篇文章,怎样通过linq返回一个结果集呢??
[解决办法]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ForWangYongB{
    class Program{
        static void Main(string[] args){
            var entities = new Entity[8];
            entities[0] = new Entity("标题1","国内新闻", 1);
            entities[1] = new Entity("标题2", "国内新闻", 2);
            entities[2] = new Entity("标题3", "国内新闻", 3);
            entities[3] = new Entity("标题1", "国际新闻", 4);
            entities[4] = new Entity("标题2", "国际新闻", 5);
            entities[5] = new Entity("标题3", "国际新闻", 6);
            entities[6] = new Entity("标题1", "火星新闻", 7);
            entities[7] = new Entity("标题2", "火星新闻", 8);

            var max = entities.GroupBy(x => x.Class)//按频道分类
                .SelectMany(x => x.OrderByDescending(y=>y.Id).Take(2))//1)每个频道的文章倒序取前2条,2)实际改为Take(10)即可
                //.OrderBy(x=>x.Class)如果需要类别排序
                //.ThenBy(x=>x.Id)  如果需要ID排序
                .ToArray();

            foreach (var item in max){


                Console.WriteLine(string.Format("{0},{1}", item.Title, item.Class));
            }
            Console.ReadLine();
        }

        class Entity{
            public Entity(string title,string @class, int id){
                this.Title = title;
                this.Class = @class;
                this.Id = id;
            }
            public string Class { get; set; }
            public string Title { get; set; }
            public int Id { get; set; }
        }
    }
}


[解决办法]
view里边就直接使用
var entities = new Entity[8];
进行格式编排,输出即可啊,MVC可能简单些
[解决办法]
var maxmodel = entities.GroupBy(x => x.Class).OrderByDescending(y=>y.Id).Take(10);
return view(maxmodel);

热点排行