柚子快报邀请码778899分享:C#数据操作LINQ
Linq是language integrated query的缩写,即“语言集成查询”之意。
Linq主要包含四个组件,Linq to object、Linq to XML、Linq to Dataset和Linq to SQL。本文仅涉及前两个。
代码示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace Linq
{
class Program
{
static void Main(string[] args)
{
//初始化要查询的数据
List
for (int i = 0; i < 10; i++)
{
inputArray.Add(i);
}
Console.WriteLine("使用Linq方法来对集合对象查询,查询结果为:");
LinqQuery(inputArray);
Console.WriteLine("\n\r使用Linq方法来查询xml:\n");
LinqToXML();
Console.ReadKey();
}
//使用linq返回集合中为偶数的元素
private static void LinqQuery(List
{
var queryResult = from item in collection
where item % 2 == 0 || item == 3//组合查询条件
orderby item descending//倒序排序
select item;
//输出结果
foreach (var item in queryResult)
{
Console.WriteLine(item.ToString() + " ");
}
}
//初始化xml数据
private static string xmlstring =
@"
";
///
/// 使用Linq对XML文件进行查询
///
private static void LinqToXML()
{
//导入xml
XElement xmlDoc = XElement.Parse(xmlstring);
//创建查询,获取作者为“王小为”的元素
var queryResult = from element in xmlDoc.Elements("book")
where element.Element("author").Value == "藏锋"
select element;
//输出查询结果
foreach (var item in queryResult)
{
Console.WriteLine("书名:" + item.Element("title").Value + " 作者:" + item.Element("author").Value + " 出版社:" + item.Element("publisher").Value);
}
}
}
}
执行结果:
柚子快报邀请码778899分享:C#数据操作LINQ
发表评论