Please see the example below. The statements below is an example of a search algorithm where the loop terminates as soon as it found the search item on the list.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestSolution
{
public partial class ForeachBreak : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//creates list of string data
List lst = new List();
lst.Add("anna");
lst.Add("jun");
lst.Add("sam");
lst.Add("leila");
//set search item to search to the list
string searchItem = "jun";
//flag to know that the item been seached exist or not
bool isFound = false;
foreach (string s in lst)
{
if (s.Equals(searchItem))
{
isFound = true;
break;
}
}
//show the result
Response.Write(isFound);
}
}
}





0 comments:
Post a Comment