tags:

views:

53

answers:

1

I'm trying to find the next available Groupname on my project. I want the groupnames look like "Gruppe 1", "Gruppe 2" and so on. So that's what i got so far:

int i = 0;
while ((from GroupViewModel g in _groups
        where g.GroupName == ("Gruppe " + (++i).ToString())
        select g).Any());
Group group = new Group() { Name = string.Format("Gruppe {0}", i) };
_groups.Add(new GroupViewModel(group));

I thought this is a cool solution for my problem, but than i started testing the code.
If _groups is empty, the first group is "Gruppe 0".
If _groups contains 1 Group(named "Gruppe 1"), the resulting groupname is "Gruppe 2".
If _groups contains 1 Group(named "Gruppe 2"), the resulting groupname is "Gruppe 1", but if i add an other group the resulting name is also "Gruppe 2". I did alot testcases and the results are always strange.

initial Groupnames             | Resulting names
-empty-                        | "Gruppe 0", "Gruppe 1", "Gruppe 2", ...
"Gruppe 1"                     | "Gruppe 2", "Gruppe 3", "Gruppe 4", ...
"Gruppe 2"                     | "Gruppe 1", "Gruppe 2", "Gruppe 3", ...
"Gruppe 1", "Gruppe 2"         | "Gruppe 3", "Gruppe 4", "Gruppe 5", ...
"Gruppe 1", "Gruppe 3"         | "Gruppe 5", "Gruppe 6", "Gruppe 7", ...
"Gruppe 1", "Gruppe 4"         | "Gruppe 3", "Gruppe 4", "Gruppe 5", ...
"Gruppe 2", "Gruppe 1"         | "Gruppe 2", "Gruppe 3", "Gruppe 4", ...

So, any clues?

+6  A: 

Well, i++ is being called for every entry, whether or not it matches.

I would suggest creating a lookup by the group name, and then just using a loop to extract the results. However, it's really not clear to me what you want in the first place. Are you just trying to find the first "available" group ID and add a new GroupViewModel for it? If so, I'd do something like:

var lookup = _groups.ToLookup(group => group.GroupName);

for (int i=0; i < int.MaxValue; i++)
{
    string candidateName = "Gruppe " + i;
    if (!lookup.Contains(candidateName)
    {
        Group group = new Group { Name = candidateName };
        _groups.Add(new GroupViewModel(group));
        break;
    }
}
Jon Skeet
Thanks a lot. Yes, that's exactly what i want to do. (btw u missed the "i++")
Marcel Benthin
Whoops - thanks, fixed :)
Jon Skeet