C# LINQ
Lnaguage Intergrated Query(Linq) 集成查询语言
基本查询表达式模式来查询和转换 SQL 数据库、ADO.NET 数据集、XML 文档和流以及 .NET 集合中的数据
Linq语句的三个步骤:
1.定义数据源;
2.定义查询语句;
3.执行查询语句。
sample1
class LINQQueryExpressions
{
static void Main()
{
// 定义数据源
int[] scores = new int[] { 97, 92, 81, 60 };
// 定义查询语句
IEnumerable scoreQuery =
from score in scores
where score > 80
select score;
// 执行查询语句
foreach (int i in scoreQuery)
{
Console.Write(i + " ");
}
//执行query语句的其他方法
//scoreQuery.ToList();
//scoreQuery.ToArray();
}
}
query语句在没有使用到这个数据集的时候,是没有执行的,这里需要注意数据调用的先后顺序。以免造成错误。
查询两种方法
query语句形式,方法的形式
query语句形式如sample1所示。
方法的形式
var ScoreQuery2=Scores where(score=>score>80)
order by(score=>score);
在上面的查询中,用到的是int型数据这里转换到string类型,代码如下:
IEnumerable highScoresQuery2 =
from score in scores
where score > 80
orderby score descending
select String.Format("The score is {0}", score);
由于查询存储了结果,已经是一个元素集,在程序中不能将查询变量单纯看为一个变量。
select,group,into关键字
// percentileQuery is an IEnumerable>
var percentileQuery =
from country in countries
let percentile = (int) country.Population / 10000000
group country by percentile into countryGroup
where countryGroup.Key >= 20
orderby countryGroup.Key
select countryGroup;
// grouping is an IGrouping
foreach (var grouping in percentileQuery)
{
Console.WriteLine(grouping.Key);
foreach (var country in grouping)
Console.WriteLine(country.Name + ":" + country.Population);
}
where子句
IEnumerable queryCityPop =
from city in cities
where city.Population < 200000 && city.Population > 100000
select city;
orderby 子句
IEnumerable querySortedCountries =
from country in countries
orderby country.Area, country.Population descending
select country;
Join子句集合之间的连接,左连接,右连接。
var categoryQuery =
from cat in categories
join prod in products on cat equals prod.Category
select new { Category = cat, Name = prod.Name };
let子句
string[] names = { "Svetlana Omelchenko", "Claire O'Donnell", "Sven Mortensen", "Cesar Garcia" };
IEnumerable queryFirstNames =
from name in names
let firstName = name.Split(new char[] { ' ' })[0]
select firstName;
foreach (string s in queryFirstNames)
Console.Write(s + " ");
子查询
var queryGroupMax =
from student in students
group student by student.GradeLevel into studentGroup
select new
{
Level = studentGroup.Key,
HighestScore =
(from student2 in studentGroup
select student2.Scores.Average())
.Max()
};