黄聪:1.LinQ初体验 简单的示例(原创)

查询表达式(LINQ)简介

LINQ是LanguageIntegrated Query的简称,它是集成在.NET编程语言中的一种特性。已成为编程语言的一个组成部分,在编写程序时可以得到很好的编译时语法检查,丰富的元数据,智能感知、静态类型等强类型语言的好处。并且它同时还使得查询可以方便地对内存中的信息进行查询而不仅仅只是外部数据源。

LINQ定义了一组标准查询操作符用于在所有基于.NET平台的编程语言中更加直接地声明跨越、过滤和投射操作的统一方式,标准查询操作符允许查询作用于所有基于IEnumerable<T>接口的源,并且它还允许适合于目标域或技术的第三方特定域操作符来扩大标准查询操作符集,更重要的是,第三方操作符可以用它们自己的提供附加服务的实现来自由地替换标准查询操作符,根据LINQ模式的习俗,这些查询喜欢采用与标准查询操作符相同的语言集成和工具支持。

我们来总体看看LINQ架构

下面我们就开始学习LinQ吧,先从最简单的Hello World开始吧:

1.      Hello LINQ测试

1. Hello LINQ测试
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黄聪 , Ltd .
//-----------------------------------------------------------

using System;
using System.Linq;

namespace LinQ初体验
{
class Program
{
staticvoid Main(string[] args)
{
// 1. Hello LINQ
HelloLINQ();
}

///<summary>
/// 1. Hello LINQ
///</summary>
///<author>
///<name>黄聪</name>
///<date>2010.12.25</date>
///</author>
privatestaticvoid HelloLINQ()
{
//声明数组
string[] greetings = { "hello world", "hello LINQ", "hello Apress" };

//查询以LINQ结束的元素
var items =
from s
in greetings
where s.EndsWith("LINQ")
select s;

//遍历输出结果
foreach (var item in items)
Console.WriteLine(item);
}
}
}

运行结果:

2.      Query XML测试

代码
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黄聪 , Ltd .
//-----------------------------------------------------------

using System;
using System.Linq;
using System.Xml.Linq;

namespace LinQ初体验
{
class Program
{
staticvoid Main(string[] args)
{
// 1.Hello LINQ
//HelloLINQ();

// 2.Query XML
QueryXML();
}

///<summary>
/// 2.Query XML
///</summary>
///<author>
///<name>黄聪</name>
///<date>2010.12.25</date>
///</author>
privatestaticvoid QueryXML()
{
//创建XML示例
XElement books = XElement.Parse(
@"<books>
<book>
<title>Pro LINQ: Language Integrated Query in C# 2008</title>
<author>Joe Rattz</author>
</book>
<book>
<title>Pro WF: Windows Workflow in .NET 3.0</title>
<author>Bruce Bukovics</author>
</book>
<book>
<title>Pro C# 2005 and the .NET 2.0 Platform, Third Edition</title>
<author>Andrew Troelsen</author>
</book>
</books>
");

//查询book节点中作者为Joe Rattz的书的标题
var titles =
from book
in books.Elements("book")
where (string)book.Element("author") =="Joe Rattz"
select book.Element(
"title");

//遍历输出结果
foreach (var title in titles)
Console.WriteLine(title.Value);
}
}
}

运行结果:

3.      LinQ To Object测试

代码
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黄聪 , Ltd .
//-----------------------------------------------------------

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

namespace LinQ初体验
{
class Program
{
staticvoid Main(string[] args)
{
// 1.Hello LINQ
//HelloLINQ();

// 2.Query XML
//QueryXML();

// 3.LinQ To Object
LinQToObject();
}

///<summary>
/// 3.LinQ To Object
///</summary>
///<author>
///<name>黄聪</name>
///<date>2010.12.25</date>
///</author>
privatestaticvoid LinQToObject()
{
//新建测试数据
List<Person> persons =new List<Person>();
persons.Add(
new Person() { Name ="zhang san", Age =12 });
persons.Add(
new Person() { Name ="li si", Age =20 });
persons.Add(
new Person() { Name ="wang wu", Age =12 });
persons.Add(
new Person() { Name ="lao liu", Age =32 });
persons.Add(
new Person() { Name ="huang cong", Age =22 });
persons.Add(
new Person() { Name ="qian qi", Age =7 });
persons.Add(
new Person() { Name ="zhang qi", Age =12 });
persons.Add(
new Person() { Name ="lu san", Age =20 });

var ps
= persons.Where(p => p.Age <20);

foreach (var p in ps)
Console.WriteLine(p.ToString());
}
}
}

运行结果:

除了上面这些功能,LinQ还可以实现以下功能:

1.      数据类型转换

2.      对数组进行排序

3.      对象数组的转换

下面是对各个功能的示例讲解:

1.      数据类型转换

数据类型转换
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黄聪 , Ltd .
//-----------------------------------------------------------

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

namespace LinQ初体验
{
class Program
{
staticvoid Main(string[] args)
{
// 1.Hello LINQ
//HelloLINQ();

// 2.Query XML
//QueryXML();

// 3.LinQ To Object
//LinQToObject();

// 4.数据类型转换
StringsToInts();
}

///<summary>
/// 4.数据类型转换
///</summary>
///<author>
///<name>黄聪</name>
///<date>2010.12.25</date>
///</author>
privatestaticvoid StringsToInts()
{
string[] numbers = { "0042", "010", "9", "27" };

//将字符串数组转换为整数类型数组
int[] nums = numbers.Select(s => Int32.Parse(s)).ToArray();

foreach (int num in nums)
Console.WriteLine(num);
}
}
}

2.      对数组进行排序

代码
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黄聪 , Ltd .
//-----------------------------------------------------------

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

namespace LinQ初体验
{
class Program
{
staticvoid Main(string[] args)
{
// 1.Hello LINQ
//HelloLINQ();

// 2.Query XML
//QueryXML();

// 3.LinQ To Object
//LinQToObject();

// 4.数据类型转换
//StringsToInts();

// 5.对数组进行排序
SortArray();
}

///<summary>
/// 5.对数组进行排序
///</summary>
///<author>
///<name>黄聪</name>
///<date>2010.12.25</date>
///</author>
privatestaticvoid SortArray()
{
//排序
int[] nums =newint[] { 123, 3, 34, 54, 23, 34 };

nums
= nums.OrderBy(n => n).ToArray();

foreach (int num in nums)
Console.WriteLine(num);
}
}
}

运行结果:

3.  对象数组的转换

代码
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黄聪 , Ltd .
//-----------------------------------------------------------

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

namespace LinQ初体验
{
class Program
{
staticvoid Main(string[] args)
{
// 1.Hello LINQ
//HelloLINQ();

// 2.Query XML
//QueryXML();

// 3.LinQ To Object
//LinQToObject();

// 4.数据类型转换
//StringsToInts();

// 5.对数组进行排序
//SortArray();

// 6.对象数组的转换
ObjectConvert();
}

///<summary>
/// 6.对象数组的转换
///</summary>
///<author>
///<name>黄聪</name>
///<date>2010.12.25</date>
///</author>
privatestaticvoid ObjectConvert()
{
//新建测试数据
List<Person> persons =new List<Person>();
persons.Add(
new Person() { Name ="zhang san", Age =12 });
persons.Add(
new Person() { Name ="li si", Age =20 });
persons.Add(
new Person() { Name ="wang wu", Age =12 });
persons.Add(
new Person() { Name ="lao liu", Age =32 });
persons.Add(
new Person() { Name ="huang cong", Age =22 });
persons.Add(
new Person() { Name ="qian qi", Age =7 });
persons.Add(
new Person() { Name ="zhang qi", Age =12 });
persons.Add(
new Person() { Name ="lu san", Age =20 });

//将Person列表转换为Contact列表
List<Contact> contacts = persons
.Cast
<Person>()
.Select(e
=>new Contact
{
Info
=string.Format("姓名:{0} \t\t年龄:{1}", e.Name, e.Age)
}).ToList();

foreach (Contact contact in contacts)
Console.WriteLine(contact.Info);
}
}
}

运行结果:

好了,这些算是Linq基础示例,本人也是刚刚开始学习Linq,

本文仅提供给与我一样的初学者作为参考,高手们请不要喷饭哈,如果有错误的地方还请各位见谅~~

其中示例中用到的两个类有:

Person类:

Person
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黄聪 , Ltd .
//-----------------------------------------------------------

using System;

namespace LinQ初体验
{
///<summary>
/// Person
///
/// 修改纪录
///
/// 2008.01.11 版本:1.0 黄聪 创建。
///
/// 版本:1.0
///
///<author>
///<name>黄聪</name>
///<date>2010.11.27</date>
///</author>
///</summary>
publicclass Person
{
privatestring _name =string.Empty;
privateint _age =0;

///<summary>
/// 姓名
///</summary>
publicstring Name
{
get { return _name; }
set { _name = value; }
}

///<summary>
/// 年龄
///</summary>
publicint Age
{
get { return _age; }
set { _age = value; }
}

publicoverridestring ToString()
{
return String.Format("姓名:{0} \t\t年龄{1}", this._name, this._age);
}
}
}

Contact类

Contact
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黄聪 , Ltd .
//-----------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinQ初体验
{
///<summary>
/// Contact
///
/// 修改纪录
///
/// 2008.01.11 版本:1.0 黄聪 创建。
///
/// 版本:1.0
///
///<author>
///<name>黄聪</name>
///<date>2010.11.27</date>
///</author>
///</summary>
publicclass Contact
{
privatestring _info =string.Empty;

///<summary>
/// 个人信息
///</summary>
publicstring Info
{
get { return _info; }
set { _info = value; }
}
}
}

文章转自:http://www.cnblogs.com/huangcong/archive/2010/12/25/1916739.html

原文地址:https://www.cnblogs.com/mili3/p/2948572.html