1. 程式人生 > >Linq 多條件組合拼接排序

Linq 多條件組合拼接排序

<%@ WebHandler Language="C#" Class="Huifang" %>

using System;
using System.Web;
using Uzai.Shop.Entity.comment;
using System.Collections.Generic;
using Uzai.Shop.BLL.comment;
using System.Linq;
using System.Web.Script.Serialization;

/// <summary>
/// tanyong 2013-09-18
/// </summary>
public class Huifang : IHttpHandler {
    #region 自定義變數
    TalkBackBLL talkbll = new TalkBackBLL();
    #endregion

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        string startDate = context.Request.QueryString["sDate"];
        string endDate = context.Request.QueryString["eDate"];
        string index = context.Request.QueryString["act"];

        List<ProTalkBackEntity> list = talkbll.GetProTalkBack(Convert.ToDateTime(startDate), Convert.ToDateTime(endDate));
        List<ProTalkBackEntity> proList = new List<ProTalkBackEntity>();

        var query = list.GroupBy(t => t.ProductName).Select(p => new
        {
            ProductName = p.Key,
            hascomment = p.Sum(x => x.hascomment),
            Ding = p.Sum(x => x.Ding),
            Zan = p.Sum(x => x.Zan)
        });

        if (index == "0")//點評
            query = query.OrderByDescending(t => t.hascomment);
        else if (index == "1")//頂
            query = query.OrderByDescending(t => t.Ding);
        else//贊
            query = query.OrderByDescending(t=>t.Zan);

        query = query.Take(10).ToList();// 贊,頂,點評最大的前10條資料
        
        foreach (var item in query)
        {
            proList.Add(new ProTalkBackEntity() { ProductName = item.ProductName, hascomment = item.hascomment, Ding = item.Ding, Zan = item.Zan });
        }
        JavaScriptSerializer json = new JavaScriptSerializer();
        string result = json.Serialize(proList);
        context.Response.Write(result);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}