C# 2.0 - 有没有办法用生成的迭代器块执行“GroupBy”?
我正在使用 C# 2.0 应用程序,因此 linq/lambda 答案在这里没有帮助。
基本上我面临着一种情况,我需要yield return
一个对象,但仅如果它的属性是唯一的(分组依据)。例如,假设我有一个用户集合,并且我想要一个基于名称的分组集合(我可能有 20 个 Dave,但我只想在我的集合中看到一个)。
现在我可以想到很多情况下这可能有用,但我认为如果没有我明确地跟踪我使用另一个内部列表生成的内容,这在 C# 2.0 中是不可能的。要做到这一点,我需要访问之前生成的集合来检查它们是否存在。
是我想太多还是有道理?也许通过 IEnumerable
IEnumerable<User> UsersByNameGroup(User userToGroupBy)
{
foreach(User u in Users)
{
if(!yield.Find(delegate(User u){return u.Name == userToGroupBy.Name;})) yield return u;
}
}
I'm working with a C# 2.0 app so linq/lambda answers will be no help here.
Basically I'm faced with a situation where i need to yield return
an object but only if one if it's properties is unique (Group By). For example,..say i have a collection of users and i want a grouped collection based on name (i might have 20 Daves but I'd only want to see one in my collection).
Now i can think of a bunch of situations where this might be useful but I don't think it's possible in C# 2.0 without my explicitly keeping track of what I'm yielding with another internal list. To do it without I'd need to have access to the previously yielded set to check if they exist.
Am I over-thinking this or does it make sense? Maybe having access to the yield through the IEnumerable<T>
interface would make sense so you'd be able to do something like this-
IEnumerable<User> UsersByNameGroup(User userToGroupBy)
{
foreach(User u in Users)
{
if(!yield.Find(delegate(User u){return u.Name == userToGroupBy.Name;})) yield return u;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,您必须在内部跟踪生成的元素。但请注意,基于哈希的查找数据结构(字典等)足以用于检测重复项。
(附带说明:在 .NET 3.5 中,有内置的
GroupBy
-Methods)No, you'll have to keep track of the generated elements internally. But note that a hash-based lookup datastructure (Dictionary etc.) is sufficient for the purpose of detecting duplicates.
(As a side note: In .NET 3.5, there are builtin
GroupBy
-Methods)