Razor Pages でのwhileループを紹介します。
概要
書式
コードブロック内で下記の書式を利用します。
記述例
while (j <= 10){
j++;
}
while (true){
if (exitflag == true) break;
}
プログラム
ASP.NET Core アプリケーションを作成します。
コード
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace RazorPagesControlFlow
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
Pagesフォルダ内に"SimpleWhileLoop.cshtml" の名称で Razor Pagesを作成します。
@page
<h3>Whileループのデモ</h3>
<p>テスト</p>
@{
int i = 100;
while (i <120) {
<p>テキスト: @i</p>
if (i % 2 == 0) i = i + 3; else i = i + 1;
}
}
<p>ページの終わり</p>
解説
cshtmlファイル内の下記コードが while ループのコードになります。
ループの手前で変数iの値を100に設定します。ループではiの値が120より小さい限りはループを繰り返します。ループ内では「テキスト」の文字列と変数iの値を表示します。
変数iの値が偶数の場合はiに3を加算し、奇数の場合は、iに1を加算してループを繰り返します。
@{
int i = 100;
while (i <120) {
<p>テキスト: @i</p>
if (i % 2 == 0) i = i + 3; else i = i + 1;
}
}
実行結果
プロジェクトを実行します。
https://アプリケーションルートURL/SimpleWhileLoop
のURLを開きます。下図のページが表示されます。
ループの処理が実行されていることが確認できます。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2021-12-15
作成日: 2020-02-27