LinQ可以方便的查询对象集合
先来一个简单的例子
结果
当然,你也可以用传统的方式实现他
那么,我们为什么还要采用LinQ呢?
想一下,如果我们按照以下格式显示结果呢?
如果我们采用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);
}
{
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
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);
}
}
{
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
需要按照字数分组并排序,如果使用传统的方法将是很痛苦的一件事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);
}
}
{
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);
}
}