想运行本程序,请先做好准备工作,请参考:Linq学习__00__准备工作
(1)在HomeController中新建Index3方法如代码1.1
代码1.1
#region 用查询表达式和方法查询实现同样的查询
/// <summary>
/// 访问地址 Home/Index3
/// orderby,Where(),OrderBy(),OrderByDescending()
/// </summary>
/// <returns></returns>
public ActionResult Index3()
{
//*********************************第一组开始*********************************
int[] numbers = { 5, 10, 8, 3, 6, 12 };
//用查询表达式
IEnumerable<int> numQuery1 =from num in numbers
where num % 2 == 0
orderby num ascending//默认是升序ascending,可以不写
select num;
ViewBag.numQuery1 = numQuery1;
//用方法查询
IEnumerable<int> numQuery2 = numbers.Where(num => num % 2 == 0).OrderBy(n => n);//默认是升序OrderBy
ViewBag.numQuery2 = numQuery2;
//*********************************第一组结束*********************************
//*********************************第二组开始*********************************
var numQuery3 = from num in numbers
orderby num descending//降序descending
where num > 5 && num < 13
select num;
ViewBag.numQuery3 = numQuery3;
var numQuery4 = numbers.Where(num => (num > 5 && num < 13)).OrderByDescending(n => n);//降序OrderByDescending,升序可不是OrderByAscending,而是OrderBy
ViewBag.numQuery4 = numQuery4;
//*********************************第二组结束*********************************
//*********************************第三组开始*********************************
var numQuery5 = from num in numbers
where num > 10 || num <= 6
select num;
ViewBag.numQuery5 = numQuery5;
var numQuery6 = numbers.Where(num => (num > 10 || num <= 6));
ViewBag.numQuery6 = numQuery6;
//*********************************第三组结束*********************************
//*********************************第四组开始*********************************
//*********************************第四组结束*********************************
//*********************************第五组开始*********************************
//*********************************第五组结束*********************************
return View();
}
#endregion 用查询表达式和方法查询实现同样的查询
2)添加视图Index3.cshtml,代码如代码1.2
代码1.2
@{
ViewBag.Title = "Index3";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@{
<div style=" background-color: pink;">第一组:查询能被2整除的数</div>
<div style=" background-color: Yellow;">
用查询表达式where orderby</div>
foreach (var i in ViewBag.numQuery1)
{
<div>@i</div>
}
<div style=" background-color: Yellow;">
用方法查询where orderby</div>
foreach (var j in ViewBag.numQuery2)
{
<div>@j</div>
}
<div style=" background-color: pink;">第二组:查询大于5小于13的数</div>
<div style=" background-color: Yellow;">
用查询表达式where与运算符&&</div>
foreach (var k in ViewBag.numQuery3)
{
<div>@k</div>
}
<div style=" background-color: Yellow;">
用方法查询where与运算符&&</div>
foreach (var m in ViewBag.numQuery4)
{
<div>@m</div>
}
<div style=" background-color: pink;">第三组:查询大于10或小于等于6的数</div>
<div style=" background-color: Yellow;">
用查询表达式或运算符||</div>
foreach (var n in ViewBag.numQuery5)
{
<div>@n</div>
}
<div style=" background-color: Yellow;">
用方法查询或运算符||</div>
foreach (var p in ViewBag.numQuery6)
{
<div>@p</div>
}
<div style=" background-color: pink;">第四组</div>
<div style=" background-color: pink;">第五组</div>
}