看Linq代码产生的震撼
1. 实体类可以这样定义
2. 数组可以这样操作
3. 匿名类型(anonymous type)
4. XML可以这样操作
5. 支持比较复杂的分组操作
http://code.google.com/p/linqinaction-csharp-sample/
public class PersonInfo
{
public bool IsOnline { get; set; }
public string Name { get; set; }
public int Id { get; set; }
}
{
public bool IsOnline { get; set; }
public string Name { get; set; }
public int Id { get; set; }
}
2. 数组可以这样操作
string[] words = { "hello", "wonderful", "linq", "beautiful", "world" };
// Get only short words
var shortWords =
from word in words
where word.Length <= 5
select word;
// Print each word out
foreach (var word in shortWords)
Console.WriteLine(word);
// Get only short words
var shortWords =
from word in words
where word.Length <= 5
select word;
// Print each word out
foreach (var word in shortWords)
Console.WriteLine(word);
3. 匿名类型(anonymous type)
var books = new[] {
new {Title="Ajax in Action", Publisher="Manning", Year=2005 },
new {Title="Windows Forms in Action", Publisher="Manning", Year=2006 },
new {Title="RSS and Atom in Action", Publisher="Manning", Year=2006 }
};
new {Title="Ajax in Action", Publisher="Manning", Year=2005 },
new {Title="Windows Forms in Action", Publisher="Manning", Year=2006 },
new {Title="RSS and Atom in Action", Publisher="Manning", Year=2006 }
};
4. XML可以这样操作
//对象books在3中初始化
XElement xml = new XElement("books",
from book in books
where book.Year == 2006
select new XElement("book",
new XAttribute("title", book.Title),
new XElement("publisher", book.Publisher)
)
);
XElement xml = new XElement("books",
from book in books
where book.Year == 2006
select new XElement("book",
new XAttribute("title", book.Title),
new XElement("publisher", book.Publisher)
)
);
5. 支持比较复杂的分组操作
string[] words = { "hello", "wonderful", "linq", "beautiful", "world" };
// Group words by length
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 };
// Print each group out
foreach (var group in groups)
{
Console.WriteLine("Words of length " + group.Length);
foreach (string word in group.Words)
Console.WriteLine(" " + word);
}
// Group words by length
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 };
// Print each group out
foreach (var group in groups)
{
Console.WriteLine("Words of length " + group.Length);
foreach (string word in group.Words)
Console.WriteLine(" " + word);
}
http://code.google.com/p/linqinaction-csharp-sample/