看Linq代码产生的震撼

1. 实体类可以这样定义
public class PersonInfo
    {
        
public bool IsOnline { getset; }
        
public string Name { getset; }
        
public int Id { getset; }
    }


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);


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 }
    };


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)
      )
    );


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);
    }



http://code.google.com/p/linqinaction-csharp-sample/
posted @ 2009-01-19 18:48  高天蒲  阅读(718)  评论(5编辑  收藏  举报
[url=http://t.sina.com.cn/1084588625?s=6uyXnP][img]http://service.t.sina.com.cn/widget/qmd/1084588625/a57ab42b/1.png[/img][/url]