日期:2014-05-18  浏览次数:20467 次

关于循环的问题
我想实现这么一个效果,我的页面的连接是

index.aspx?page=这里是页码

我想实现的是,当page获得的值是 1-10之内,则在某个地方显示的是1 2 3 4 5 6 7 8 9 10
相同的,如果是11-20之间,则显示是 11 12 13...20
类推
我现在的写法是

int page;
if (page>=1 && page<=10){
string strBody = "1 2 3 4 5 6 7 8 9 10";
}
else if (page>=11 && page<=20){
string strBody = "11 12 13...20";
}
else if()...

这样下去,但是如果页码很大的时候,要不断的家else if,这样做起来就是一个蠢办法了,我想请问下,我想精简下这个,就通过一个 if实现,请问该怎么做呢?

if (page>=变量A && page<=变量B){
string strBody = "变量C";
}

具体该怎么写呢?谢谢


------解决方案--------------------
C# code


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int startnum = 1;
        int endnum = 30;
        int page = 30;
        int offset = 10;
        Response.Write(PageNav(startnum,endnum,page, offset));
    }

    /// <summary>
    /// 分页列表
    /// </summary>
    /// <param name="startnum">页码起始计数</param>
    /// <param name="endnum">最大页码</param>
    /// <param name="page">当前页码</param>
    /// <param name="offset">显示页码范围</param>
    /// <returns></returns>
    private string PageNav(int startnum, int endnum, int page, int offset)
    {
        if (page < startnum) page = startnum;
        if (page > endnum) page = endnum;

        // 取整
        int i = page / offset;
        if ((page % offset) == 0) i--;
        StringBuilder sb = new StringBuilder();
        if (i > 0) sb.Append(startnum.ToString() + "...");

        sb.Append(loop(i * offset, (i + 1) * offset));

        if (i < ((endnum / offset)-1)) sb.Append("..." + endnum.ToString());
        return sb.ToString();
    }

    /// <summary>
    /// 页码循环
    /// </summary>
    /// <param name="startnum">起始循环数</param>
    /// <param name="offset">循环次数</param>
    /// <returns></returns>
    private string loop(int startnum, int offset)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = startnum+1; i <= offset; i++)
        {
            sb.Append(i.ToString() + " ");
        }
        return sb.ToString();
    }

}