C# 中Linq的学习(查询表达式基础知识)示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LinqStudy
{
//***********************************************************************************************************
//Module:Program.cs
//Author:factly
//Create Date:2008-06-24
//***********************************************************************************************************
class Program
{
static void Main(string[] args)
{
LinqQuery linqQuery = new LinqQuery();
linqQuery.OrderbyScoresQuery();
linqQuery.HighScoresQuery();
linqQuery.ScoresQueryCount();
Console.ReadKey();
}
}
//***********************************************************************************************************
//Module:LinqOrderby.cs
//Author:factly
//Create Date:2008-06-24
//***********************************************************************************************************
class LinqQuery
{
/// <summary>
/// 返回值为void时的写法。排序(降序)
/// </summary>
/// <returns></returns>
public int? OrderbyScoresQuery()
{
int[] scores = new int[] { 88, 79, 61, 59, 74, 58, 49, 97, 99, 84 };
if (scores.Length != 0)
{
//var scoresQuery = from score in scores where score > 70 orderby score descending select score;//查询语法
var scoresQuery = scores.Where(score => score > 70).OrderByDescending(score => score);//Lambda表达式(方法语法)
Console.WriteLine("下面的数据按降序排列");
foreach (var i in scoresQuery)
{
Console.WriteLine(i);
}
Console.WriteLine("数据输出已完成!");
return 0;
}
else
{
return null;
}
}
/// <summary>
/// 从int 到 string 的转换
/// </summary>
/// <returns></returns>
public int? HighScoresQuery()
{
int[] scores = new int[] { 88, 79, 61, 59, 74, 58, 49, 97, 99, 84 };
if (scores.Length != 0)
{
//var scoresQuery = from score in scores where score > 70 orderby score descending select string.Format("The Score is {0}", score);//查询语法
var scoresQuery = scores.Where(score => score > 70).OrderByDescending(score => score);//Lambda表达式(方法语法)
Console.WriteLine("下面的数据是从int 到 string 的转换");
foreach (var i in scoresQuery)
{
Console.WriteLine(i);
}
Console.WriteLine("数据输出已完成!");
return 0;
}
else
{
return null;
}
}
/// <summary>
/// 下面的查询从 scores 整数数组中返回高于 70 的分数的数量
/// </summary>
/// <returns></returns>
public int? ScoresQueryCount()
{
int[] scores = new int[] { 88, 79, 61, 59, 74, 58, 49, 97, 99, 84 };
if (scores.Length != 0)
{
//var scoresQueryCount = (from score in scores where score > 70 select score).Count();//查询语法
var scoresQueryCount = scores.Where(score => score > 70).Count();//Lambda表达式(方法语法)
Console.WriteLine("下面数据是计算得到数据的count");
Console.WriteLine(scoresQueryCount);
Console.WriteLine("数据输出已完成!");
return 0;
}
else
{
return null;
}
}
}
}