IEnumerable
本文关键字:Arity 泛型类型定义 lt int IEnumerable | 更新日期: 2023-09-27 18:11:11
我有一个类Counter按键计数。简化:
public class Counter<T> {
private Dictionary<T, int> counts;
public void Increment(T key) {
int current;
bool exists = counts.TryGetValue(key, out current);
if (exists) {
counts[key]++;
} else {
counts[key] = 1;
}
}
}
它做了许多其他的事情专门为我的需要,但这是本质。到目前为止,它工作得很好。
现在我想使它能够在Linq查询中使用(包括键和值)。为此,我想我需要实现
IEnumerable<T, int>
所以我加了:
public class Counter<T> : IEnumerable<KeyValuePair<T, int>> {
// ...
IEnumerator<KeyValuePair<T, int>>
IEnumerable<KeyValuePair<T, int>>.GetEnumerator()
{
return ((IEnumerable<KeyValuePair<T, int>>)counts).GetEnumerator();
}
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return counts.GetEnumerator();
}
这将导致编译错误
提供的泛型实参个数不等于泛型类型定义的实参个数。参数名称:instantiation
- 什么是arity?
- 我在正确的道路上,使这种类型可从Linq?
- 我如何修复实现?
:错误
我有一个错别字,而简化我的代码张贴。代码实际上是试图实现IEnumerable<KeyValuePair<T, int>>
而不是IEnumerable<T, int>
- Arity是"参数数量"的一种奇特的说法。这就是"二进制"(接受两个参数)、"一元"(接受一个参数)和"三元"(接受三个参数)的词根。
不,不完全是:LINQ根植于函数式编程,而函数式编程讨厌所有状态,更喜欢没有副作用的函数。不幸的是,你的计数器保持状态:那是你修改的counts
字典,这是一个副作用。- 如果你想按键计数,LINQ已经提供了足够的功能。
下面是如何通过键获取项目计数的方法:
var counters = keyedData
.GroupBy(item => item.MyKey)
.ToDictionary(g => g.Key, g => g.Count());
本文关键字:Arity 泛型类型定义 lt int IEnumerable | 更新日期: 2023-09-27 18:11:11
我有一个类Counter按键计数。简化:
public class Counter<T> {
private Dictionary<T, int> counts;
public void Increment(T key) {
int current;
bool exists = counts.TryGetValue(key, out current);
if (exists) {
counts[key]++;
} else {
counts[key] = 1;
}
}
}
它做了许多其他的事情专门为我的需要,但这是本质。到目前为止,它工作得很好。
现在我想使它能够在Linq查询中使用(包括键和值)。为此,我想我需要实现
IEnumerable<T, int>
所以我加了:
public class Counter<T> : IEnumerable<KeyValuePair<T, int>> {
// ...
IEnumerator<KeyValuePair<T, int>>
IEnumerable<KeyValuePair<T, int>>.GetEnumerator()
{
return ((IEnumerable<KeyValuePair<T, int>>)counts).GetEnumerator();
}
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return counts.GetEnumerator();
}
这将导致编译错误
提供的泛型实参个数不等于泛型类型定义的实参个数。参数名称:instantiation
- 什么是arity?
- 我在正确的道路上,使这种类型可从Linq?
- 我如何修复实现?
:错误
我有一个错别字,而简化我的代码张贴。代码实际上是试图实现IEnumerable<KeyValuePair<T, int>>
而不是IEnumerable<T, int>
- Arity是"参数数量"的一种奇特的说法。这就是"二进制"(接受两个参数)、"一元"(接受一个参数)和"三元"(接受三个参数)的词根。 不,不完全是:LINQ根植于函数式编程,而函数式编程讨厌所有状态,更喜欢没有副作用的函数。不幸的是,你的计数器保持状态:那是你修改的
- 如果你想按键计数,LINQ已经提供了足够的功能。
counts
字典,这是一个副作用。下面是如何通过键获取项目计数的方法:
var counters = keyedData
.GroupBy(item => item.MyKey)
.ToDictionary(g => g.Key, g => g.Count());