Linq案例
1.牛刀小试
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace linq
{
class Program
{
static void Main(string[] args)
{
string[] words = { "hello","linq","good","wonderful"};
var shortWords = from word in words
where word.Length <= 5
select word;
foreach (var word in shortWords)
{
Console.WriteLine(word);
}
Console.ReadKey();
}
}
}
2.Group分组处理
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace linq
{
class Program
{
static void Main(string[] args)
{
string[] words = { "hello","linq","good","wonderful","world","beautiful"};
//VAR 是3.5新出的一个定义变量的类型,其实也就是弱化类型的定义。VAR可代替任何类型,编译器会根据上下文来判断你到底是想用什么类型的。
var groups = from word in words
orderby word ascending
group word by word.Length into lengthGroups
orderby lengthGroups.Key descending
select new { Length = lengthGroups.Key, Words = lengthGroups }; // 按长度将单词分组
foreach (var group in groups)
{
Console.WriteLine("Words of length" + group.Length);
foreach (string word in group.Words)
{
Console.WriteLine(" " + word);
}
}
Console.ReadKey();
}
}
}
3.XML 案例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Threading.Tasks;
namespace linq
{
class Book
{
public string Publisher;
public string Title;
public int Year;
public Book(string title,string publisher,int year)
{
Title = title;
Publisher = publisher;
Year = year;
}
}
class Program
{
static void Main(string[] args)
{
Book[] books = new Book[]
{
new Book("Ajax","Zhang",2015),
new Book("Java","Li",2016),
new Book(".Net","Zhao",2016),
};
XElement xml = new XElement("books",
from book in books
where book.Year == 2016
select new XElement("book",
new XAttribute("title",book.Title),
new XElement("publisher",book.Publisher)
)
);
Console.WriteLine(xml);
Console.ReadKey();
}
}
}