惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - Franky
有赞技术团队
有赞技术团队
宝玉的分享
宝玉的分享
雷峰网
雷峰网
Hugging Face - Blog
Hugging Face - Blog
V
V2EX
大猫的无限游戏
大猫的无限游戏
博客园 - 司徒正美
D
Docker
T
The Blog of Author Tim Ferriss
罗磊的独立博客
博客园 - 叶小钗
酷 壳 – CoolShell
酷 壳 – CoolShell
Blog — PlanetScale
Blog — PlanetScale
月光博客
月光博客
J
Java Code Geeks
Jina AI
Jina AI
博客园 - 【当耐特】
C
Check Point Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
腾讯CDC
Last Week in AI
Last Week in AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
Visual Studio Blog

博客园 - 滋心

为hover事件加上延迟 面向对象的JavaScript(2)闭包 面向对象的JavaScript(1):创建简单的类 JQuery画细线表格 自定义控件验证页面所有文本框 - 滋心 - 博客园 LinQ in Action 笔记三:Hello LINQ to SQL LinQ in Action 笔记二:Hello LINQ to XML JQuery选择器插件 Extra selectors JQuery选择器 - 滋心 - 博客园 利用Repeater控件显示主-从关系数据表 查询表结构 Sqlserver建立和另外数据库的连接 XPath实例教程十九、ancestor-or-self 轴(axis)包含上下文节点本身和该节点的祖先节点 XPath实例教程十八、descendant-or-self 轴 XPath实例教程十七、preceding轴 XPath实例教程十六、following轴 XPath实例教程十五、preceding-sibling 轴 XPath实例教程十四、following-sibling轴 XPath实例教程十三、ancestor轴
LinQ in Action 笔记一、Hello LINQ to Objects
滋心 · 2008-07-04 · via 博客园 - 滋心

LinQ可以方便的查询对象集合

先来一个简单的例子

static void Main()
{
    
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);
}

结果

hello
linq
world

当然,你也可以用传统的方式实现他

static void Main()
{
  
string[] words = new string[] { "hello""wonderful""linq",
                                  
"beautiful""world" };
   
foreach (string word in words)
  {
    
if (word.Length <= 5)
      Console.WriteLine(word);
  }
}

那么,我们为什么还要采用LinQ呢?
想一下,如果我们按照以下格式显示结果呢?

Words of length 9
beautiful
wonderful
Words of length 
5
hello
world
Words of length 
4
linq

需要按照字数分组并排序,如果使用传统的方法将是很痛苦的一件事
如果我们采用LinQ来查询将很简单

static void Main()
{
  
string[] words = { "hello""wonderful""linq""beautiful""world" };
   
// 按照单词的字数分组
  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);
  }
}