views:

52

answers:

1

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;
    } 
}

All help will be appreciated.

Thanks in advance.

+1  A: 

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)

Dario
Yeah, the GroupBy extension method is what prompted the question but I'm stuck on 2.0 on this project,..it's not my decision. I can't use HashSet either since that's a 3.5ism unless i reference System.Core.
Stimul8d