在 C# 中,Lookup 和 ToLookup 方法都是用于将一个序列分组并返回一个 ILookup 对象,但它们在实现细节上略有不同。
Lookup 方法是一个扩展方法,定义在 System.Linq 命名空间中。它接受一个序列和一个键选择器函数,返回一个 ILookup<TKey, TElement> 对象。这个对象是一个只读的键/值集合,其中每个键都与一个或多个值相关联。Lookup 方法返回的对象是基于哈希表实现的,可以快速地查找与指定键关联的所有值。
举个栗子:
string[] words = { "apple", "banana", "cherry", "date", "elderberry", "fig", "grape" };
var lookup = words.ToLookup(w => w[0]);
foreach (var group in lookup)
{
Console.WriteLine("Words that start with '{0}':", group.Key);
foreach (string word in group)
{
Console.WriteLine(" {0}", word);
}
}
在这个例子中,我们将一个字符串数组分组,使得每个分组都以相同的第一个字母开头。ToLookup 方法将每个字符串映射到以它的第一个字母为键的 IGrouping<char, string> 对象中。然后,我们可以使用 foreach 循环来遍历每个分组,并打印出分组的键和值。
var lookup = words.ToLookup(w => w[0]);
这一行定义了一个字符串数组,其中包含了一些水果的名称。
var lookup = words.ToLookup(w => w[0]);
这一行使用 ToLookup 方法将字符串数组分组,使得每个分组都以相同的第一个字母开头。具体来说,它使用 w => w[0] 作为键选择器函数,将每个字符串映射到以它的第一个字母为键的 IGrouping<char, string> 对象中。然后,它将这些对象存储到一个 ILookup<char, string> 对象中,这个对象是一个只读的键/值集合,其中每个键都与一个或多个值相关联。
foreach (var group in lookup)
{
Console.WriteLine("Words that start with '{0}':", group.Key);
foreach (string word in group)
{
Console.WriteLine(" {0}", word);
}
}
这一行使用 foreach 循环遍历每个分组,并打印出分组的键和值。具体来说,它先遍历 lookup 对象中的每个 IGrouping<char, string> 对象,即每个以相同的第一个字母开头的字符串分组。然后,对于每个分组,它打印出分组的键(即第一个字母),然后遍历分组中的每个字符串,并打印出字符串的值。
这段代码的输出如下:
Words that start with 'a':
apple
Words that start with 'b':
banana
Words that start with 'c':
cherry
Words that start with 'd':
date
Words that start with 'e':
elderberry
Words that start with 'f':
fig
Words that start with 'g':
grape
ToLookup 方法与 Lookup 方法类似,但是它是一个实例方法,定义在 IEnumerable 接口上。它接受一个键选择器函数和一个可选的元素选择器函数,并返回一个 ILookup<TKey, TElement> 对象。与 Lookup 方法不同,ToLookup 方法不需要在调用时将序列转换为数组或列表。ToLookup 方法返回的对象也是基于哈希表实现的,可以快速地查找与指定键关联的所有值。
举个栗子:
string[] words = { "apple", "banana", "cherry", "date", "elderberry", "fig", "grape" };
// 使用 ToLookup 方法,将字符串数组按照首字母分组,并且将每个字符串的长度作为值
var lookup = words.ToLookup(w => w[0], w => w.Length);
foreach (var group in lookup)
{
Console.WriteLine("Words that start with '{0}':", group.Key);
// 打印出当前分组的键和值
foreach (int length in group)
{
Console.WriteLine(" {0}", length);
}
}
在这个例子中,我们将一个字符串数组分组,使得每个分组都以相同的第一个字母开头。ToLookup 方法将每个字符串映射到以它的第一个字母为键的 IGrouping<char, int> 对象中,其中值为字符串的长度。然后,我们可以使用 foreach 循环来遍历每个分组,并打印出分组的键和值。
这段代码的输出如下:
Words that start with 'a':
5
Words that start with 'b':
6
Words that start with 'c':
6
Words that start with 'd':
4
Words that start with 'e':
10
Words that start with 'f':
3
Words that start with 'g':
5
输出了每个以相同的第一个字母开头的字符串分组,并按照字母顺序打印出分组的键和值。注意,由于只有一个字符串以 “a” 开头,因此 “a” 组只有一个字符串的长度是 5。