先来一个简单的例子
结果
当然,你也可以用传统的方式实现他
static void Main()
{
string[] words = new string[] { "hello", "wonderful", "linq",
"beautiful", "world" };
foreach (string word in words)
{
if (word.Length <= 5)
Console.WriteLine(word);
}
}
{
string[] words = new string[] { "hello", "wonderful", "linq",
"beautiful", "world" };
foreach (string word in words)
{
if (word.Length <= 5)
Console.WriteLine(word);
}
}
那么,我们为什么还要采用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);
}
}
{
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);
}
}