C# do..while loop for a list
I want to create a simple app that is showing recursive group membership, however not users but groups. So if groupA have groupB as a member and groupB have groupC as a member, I want the code to show me all the groups nested till the last one.
Here is the sample with what I have:
if (member.Any())
List<string> tempGroup = new List<string>();
do
tempGroup.Clear();
foreach (object nestedGroup in member)
SearchResult NestedGroupMemberResult = null;
try
string NestedgroupMemberSearchFilter = "(&(objectClass=group)(distinguishedName=" + nestedGroup.ToString() + "))";
string NestedgroupMemberPropertise = "member,distinguishedName";
NestedGroupMemberResult = dirSearcher(NestedgroupMemberSearchFilter, NestedgroupMemberPropertise);
catch
if(NestedGroupMemberResult.Properties["member"].Count > 0)
foreach (object NestedGroupMember in NestedGroupMemberResult.Properties["member"])
member.Add(NestedGroupMember.ToString());
tempGroup.Add(NestedGroupMember.ToString());
while (!tempGroup.Any());
listBox1.DataSource = member;
Basically member is a list which contains group members from an input group. Lets say that I initial put GroupA and it have members as GroupB and GroupC and both will be in member list. Now I would like that loop do..while searches for each member of input group using LDAP filter applied, and if it finds any group add it to both member list and tempGroup list, so each time there is a nested group, member list will be updated and at the same time it will be included in foreach loop. If app finds out that there are no more nested groups, the tempGroup list will be empty and loop will stop.
However I'm constantly receiving error "System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'" for
foreach (object nestedGroup in member)
And I guess I cannot modify member list while for loop is iterating through it. I had very similar loop in powershell that works great, but I wanted to have an c# app as I know that it can be much faster in such searches.
c# .net list do-while
|
show 2 more comments
I want to create a simple app that is showing recursive group membership, however not users but groups. So if groupA have groupB as a member and groupB have groupC as a member, I want the code to show me all the groups nested till the last one.
Here is the sample with what I have:
if (member.Any())
List<string> tempGroup = new List<string>();
do
tempGroup.Clear();
foreach (object nestedGroup in member)
SearchResult NestedGroupMemberResult = null;
try
string NestedgroupMemberSearchFilter = "(&(objectClass=group)(distinguishedName=" + nestedGroup.ToString() + "))";
string NestedgroupMemberPropertise = "member,distinguishedName";
NestedGroupMemberResult = dirSearcher(NestedgroupMemberSearchFilter, NestedgroupMemberPropertise);
catch
if(NestedGroupMemberResult.Properties["member"].Count > 0)
foreach (object NestedGroupMember in NestedGroupMemberResult.Properties["member"])
member.Add(NestedGroupMember.ToString());
tempGroup.Add(NestedGroupMember.ToString());
while (!tempGroup.Any());
listBox1.DataSource = member;
Basically member is a list which contains group members from an input group. Lets say that I initial put GroupA and it have members as GroupB and GroupC and both will be in member list. Now I would like that loop do..while searches for each member of input group using LDAP filter applied, and if it finds any group add it to both member list and tempGroup list, so each time there is a nested group, member list will be updated and at the same time it will be included in foreach loop. If app finds out that there are no more nested groups, the tempGroup list will be empty and loop will stop.
However I'm constantly receiving error "System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'" for
foreach (object nestedGroup in member)
And I guess I cannot modify member list while for loop is iterating through it. I had very similar loop in powershell that works great, but I wanted to have an c# app as I know that it can be much faster in such searches.
c# .net list do-while
1
You should not usemember.Add()insideforeachloop while still iteratingmembercollection contents. Consider read this issue: stackoverflow.com/questions/604831/….
– Tetsuya Yamamoto
Nov 15 '18 at 9:34
1
What's the question?
– phuzi
Nov 15 '18 at 9:34
Possible duplicate of What is the best way to modify a list in a 'foreach' loop?
– Jevgeni Geurtsen
Nov 15 '18 at 9:34
2
Possible duplicate of Collection was modified; enumeration operation may not execute
– Tetsuya Yamamoto
Nov 15 '18 at 9:36
The question is how can I iterate through nested groups using foreach loop, but I can see that there are some post about possible duplicate, I will check them and search for an answer.
– varrimatrass
Nov 15 '18 at 9:52
|
show 2 more comments
I want to create a simple app that is showing recursive group membership, however not users but groups. So if groupA have groupB as a member and groupB have groupC as a member, I want the code to show me all the groups nested till the last one.
Here is the sample with what I have:
if (member.Any())
List<string> tempGroup = new List<string>();
do
tempGroup.Clear();
foreach (object nestedGroup in member)
SearchResult NestedGroupMemberResult = null;
try
string NestedgroupMemberSearchFilter = "(&(objectClass=group)(distinguishedName=" + nestedGroup.ToString() + "))";
string NestedgroupMemberPropertise = "member,distinguishedName";
NestedGroupMemberResult = dirSearcher(NestedgroupMemberSearchFilter, NestedgroupMemberPropertise);
catch
if(NestedGroupMemberResult.Properties["member"].Count > 0)
foreach (object NestedGroupMember in NestedGroupMemberResult.Properties["member"])
member.Add(NestedGroupMember.ToString());
tempGroup.Add(NestedGroupMember.ToString());
while (!tempGroup.Any());
listBox1.DataSource = member;
Basically member is a list which contains group members from an input group. Lets say that I initial put GroupA and it have members as GroupB and GroupC and both will be in member list. Now I would like that loop do..while searches for each member of input group using LDAP filter applied, and if it finds any group add it to both member list and tempGroup list, so each time there is a nested group, member list will be updated and at the same time it will be included in foreach loop. If app finds out that there are no more nested groups, the tempGroup list will be empty and loop will stop.
However I'm constantly receiving error "System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'" for
foreach (object nestedGroup in member)
And I guess I cannot modify member list while for loop is iterating through it. I had very similar loop in powershell that works great, but I wanted to have an c# app as I know that it can be much faster in such searches.
c# .net list do-while
I want to create a simple app that is showing recursive group membership, however not users but groups. So if groupA have groupB as a member and groupB have groupC as a member, I want the code to show me all the groups nested till the last one.
Here is the sample with what I have:
if (member.Any())
List<string> tempGroup = new List<string>();
do
tempGroup.Clear();
foreach (object nestedGroup in member)
SearchResult NestedGroupMemberResult = null;
try
string NestedgroupMemberSearchFilter = "(&(objectClass=group)(distinguishedName=" + nestedGroup.ToString() + "))";
string NestedgroupMemberPropertise = "member,distinguishedName";
NestedGroupMemberResult = dirSearcher(NestedgroupMemberSearchFilter, NestedgroupMemberPropertise);
catch
if(NestedGroupMemberResult.Properties["member"].Count > 0)
foreach (object NestedGroupMember in NestedGroupMemberResult.Properties["member"])
member.Add(NestedGroupMember.ToString());
tempGroup.Add(NestedGroupMember.ToString());
while (!tempGroup.Any());
listBox1.DataSource = member;
Basically member is a list which contains group members from an input group. Lets say that I initial put GroupA and it have members as GroupB and GroupC and both will be in member list. Now I would like that loop do..while searches for each member of input group using LDAP filter applied, and if it finds any group add it to both member list and tempGroup list, so each time there is a nested group, member list will be updated and at the same time it will be included in foreach loop. If app finds out that there are no more nested groups, the tempGroup list will be empty and loop will stop.
However I'm constantly receiving error "System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'" for
foreach (object nestedGroup in member)
And I guess I cannot modify member list while for loop is iterating through it. I had very similar loop in powershell that works great, but I wanted to have an c# app as I know that it can be much faster in such searches.
c# .net list do-while
c# .net list do-while
asked Nov 15 '18 at 9:31
varrimatrassvarrimatrass
82
82
1
You should not usemember.Add()insideforeachloop while still iteratingmembercollection contents. Consider read this issue: stackoverflow.com/questions/604831/….
– Tetsuya Yamamoto
Nov 15 '18 at 9:34
1
What's the question?
– phuzi
Nov 15 '18 at 9:34
Possible duplicate of What is the best way to modify a list in a 'foreach' loop?
– Jevgeni Geurtsen
Nov 15 '18 at 9:34
2
Possible duplicate of Collection was modified; enumeration operation may not execute
– Tetsuya Yamamoto
Nov 15 '18 at 9:36
The question is how can I iterate through nested groups using foreach loop, but I can see that there are some post about possible duplicate, I will check them and search for an answer.
– varrimatrass
Nov 15 '18 at 9:52
|
show 2 more comments
1
You should not usemember.Add()insideforeachloop while still iteratingmembercollection contents. Consider read this issue: stackoverflow.com/questions/604831/….
– Tetsuya Yamamoto
Nov 15 '18 at 9:34
1
What's the question?
– phuzi
Nov 15 '18 at 9:34
Possible duplicate of What is the best way to modify a list in a 'foreach' loop?
– Jevgeni Geurtsen
Nov 15 '18 at 9:34
2
Possible duplicate of Collection was modified; enumeration operation may not execute
– Tetsuya Yamamoto
Nov 15 '18 at 9:36
The question is how can I iterate through nested groups using foreach loop, but I can see that there are some post about possible duplicate, I will check them and search for an answer.
– varrimatrass
Nov 15 '18 at 9:52
1
1
You should not use
member.Add() inside foreach loop while still iterating member collection contents. Consider read this issue: stackoverflow.com/questions/604831/….– Tetsuya Yamamoto
Nov 15 '18 at 9:34
You should not use
member.Add() inside foreach loop while still iterating member collection contents. Consider read this issue: stackoverflow.com/questions/604831/….– Tetsuya Yamamoto
Nov 15 '18 at 9:34
1
1
What's the question?
– phuzi
Nov 15 '18 at 9:34
What's the question?
– phuzi
Nov 15 '18 at 9:34
Possible duplicate of What is the best way to modify a list in a 'foreach' loop?
– Jevgeni Geurtsen
Nov 15 '18 at 9:34
Possible duplicate of What is the best way to modify a list in a 'foreach' loop?
– Jevgeni Geurtsen
Nov 15 '18 at 9:34
2
2
Possible duplicate of Collection was modified; enumeration operation may not execute
– Tetsuya Yamamoto
Nov 15 '18 at 9:36
Possible duplicate of Collection was modified; enumeration operation may not execute
– Tetsuya Yamamoto
Nov 15 '18 at 9:36
The question is how can I iterate through nested groups using foreach loop, but I can see that there are some post about possible duplicate, I will check them and search for an answer.
– varrimatrass
Nov 15 '18 at 9:52
The question is how can I iterate through nested groups using foreach loop, but I can see that there are some post about possible duplicate, I will check them and search for an answer.
– varrimatrass
Nov 15 '18 at 9:52
|
show 2 more comments
4 Answers
4
active
oldest
votes
There are a few approaches you could take to tackle this problem. The first one, using a temporary list, is mentioned in the answers already. The other approach is to use a for-loop. As I commented, MSDN states the following:
The foreach statement is used to iterate through the collection to get
the information that you want, but can not be used to add or remove
items from the source collection to avoid unpredictable side effects.
If you need to add or remove items from the source collection, use a
for loop.
Now some information is missing here for you to make the right, most fitting, choice. If you use a for-loop, and modify the list during enumeration, the items that you add while enumerating will be enumerated too.
So ask yourself the following question: Do the newly added items need to be enumerated too? If so, use a for-loop. If not, you probably want to use the items somewhere else and hence you need to store them somewhere else, for example, in a temporary list.
add a comment |
Don't modify the collection that you're enumerating with the foreach. Instead you could collect all things that you have to modify:
List<Object> addMembers = new List<Object>();
foreach (object nestedGroup in member)
// ...
foreach (object NestedGroupMember in NestedGroupMemberResult.Properties["member"])
addMembers.Add(NestedGroupMember.ToString());
//...
// ...
}
addMembers.ForEach(member.Add);
add a comment |
Please check this line :
member.Add(NestedGroupMember.ToString());
Maybe error occurred when this line executed because you are trying to Add NestedGroupMember.ToString() to member list that are now in a foreach loop, to solve error just create a temporarily variable for this Type just like tempGroup definition and then join them to main member list after foreach ends.
add a comment |
You are using foreach, but it doesnt allow you to modify the collection. BUT you can make a reversed for loop, like:
for (var i = list.Length - 1; i >= 0; i--
var item = list[i];
// TODO
That must work. Just replace all your foreach loops with collection modification with this reversed for.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53316272%2fc-sharp-do-while-loop-for-a-list%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
There are a few approaches you could take to tackle this problem. The first one, using a temporary list, is mentioned in the answers already. The other approach is to use a for-loop. As I commented, MSDN states the following:
The foreach statement is used to iterate through the collection to get
the information that you want, but can not be used to add or remove
items from the source collection to avoid unpredictable side effects.
If you need to add or remove items from the source collection, use a
for loop.
Now some information is missing here for you to make the right, most fitting, choice. If you use a for-loop, and modify the list during enumeration, the items that you add while enumerating will be enumerated too.
So ask yourself the following question: Do the newly added items need to be enumerated too? If so, use a for-loop. If not, you probably want to use the items somewhere else and hence you need to store them somewhere else, for example, in a temporary list.
add a comment |
There are a few approaches you could take to tackle this problem. The first one, using a temporary list, is mentioned in the answers already. The other approach is to use a for-loop. As I commented, MSDN states the following:
The foreach statement is used to iterate through the collection to get
the information that you want, but can not be used to add or remove
items from the source collection to avoid unpredictable side effects.
If you need to add or remove items from the source collection, use a
for loop.
Now some information is missing here for you to make the right, most fitting, choice. If you use a for-loop, and modify the list during enumeration, the items that you add while enumerating will be enumerated too.
So ask yourself the following question: Do the newly added items need to be enumerated too? If so, use a for-loop. If not, you probably want to use the items somewhere else and hence you need to store them somewhere else, for example, in a temporary list.
add a comment |
There are a few approaches you could take to tackle this problem. The first one, using a temporary list, is mentioned in the answers already. The other approach is to use a for-loop. As I commented, MSDN states the following:
The foreach statement is used to iterate through the collection to get
the information that you want, but can not be used to add or remove
items from the source collection to avoid unpredictable side effects.
If you need to add or remove items from the source collection, use a
for loop.
Now some information is missing here for you to make the right, most fitting, choice. If you use a for-loop, and modify the list during enumeration, the items that you add while enumerating will be enumerated too.
So ask yourself the following question: Do the newly added items need to be enumerated too? If so, use a for-loop. If not, you probably want to use the items somewhere else and hence you need to store them somewhere else, for example, in a temporary list.
There are a few approaches you could take to tackle this problem. The first one, using a temporary list, is mentioned in the answers already. The other approach is to use a for-loop. As I commented, MSDN states the following:
The foreach statement is used to iterate through the collection to get
the information that you want, but can not be used to add or remove
items from the source collection to avoid unpredictable side effects.
If you need to add or remove items from the source collection, use a
for loop.
Now some information is missing here for you to make the right, most fitting, choice. If you use a for-loop, and modify the list during enumeration, the items that you add while enumerating will be enumerated too.
So ask yourself the following question: Do the newly added items need to be enumerated too? If so, use a for-loop. If not, you probably want to use the items somewhere else and hence you need to store them somewhere else, for example, in a temporary list.
edited Nov 16 '18 at 12:15
answered Nov 15 '18 at 12:22
Jevgeni GeurtsenJevgeni Geurtsen
2,62941333
2,62941333
add a comment |
add a comment |
Don't modify the collection that you're enumerating with the foreach. Instead you could collect all things that you have to modify:
List<Object> addMembers = new List<Object>();
foreach (object nestedGroup in member)
// ...
foreach (object NestedGroupMember in NestedGroupMemberResult.Properties["member"])
addMembers.Add(NestedGroupMember.ToString());
//...
// ...
}
addMembers.ForEach(member.Add);
add a comment |
Don't modify the collection that you're enumerating with the foreach. Instead you could collect all things that you have to modify:
List<Object> addMembers = new List<Object>();
foreach (object nestedGroup in member)
// ...
foreach (object NestedGroupMember in NestedGroupMemberResult.Properties["member"])
addMembers.Add(NestedGroupMember.ToString());
//...
// ...
}
addMembers.ForEach(member.Add);
add a comment |
Don't modify the collection that you're enumerating with the foreach. Instead you could collect all things that you have to modify:
List<Object> addMembers = new List<Object>();
foreach (object nestedGroup in member)
// ...
foreach (object NestedGroupMember in NestedGroupMemberResult.Properties["member"])
addMembers.Add(NestedGroupMember.ToString());
//...
// ...
}
addMembers.ForEach(member.Add);
Don't modify the collection that you're enumerating with the foreach. Instead you could collect all things that you have to modify:
List<Object> addMembers = new List<Object>();
foreach (object nestedGroup in member)
// ...
foreach (object NestedGroupMember in NestedGroupMemberResult.Properties["member"])
addMembers.Add(NestedGroupMember.ToString());
//...
// ...
}
addMembers.ForEach(member.Add);
answered Nov 15 '18 at 9:44
RangoRango
365k46472731
365k46472731
add a comment |
add a comment |
Please check this line :
member.Add(NestedGroupMember.ToString());
Maybe error occurred when this line executed because you are trying to Add NestedGroupMember.ToString() to member list that are now in a foreach loop, to solve error just create a temporarily variable for this Type just like tempGroup definition and then join them to main member list after foreach ends.
add a comment |
Please check this line :
member.Add(NestedGroupMember.ToString());
Maybe error occurred when this line executed because you are trying to Add NestedGroupMember.ToString() to member list that are now in a foreach loop, to solve error just create a temporarily variable for this Type just like tempGroup definition and then join them to main member list after foreach ends.
add a comment |
Please check this line :
member.Add(NestedGroupMember.ToString());
Maybe error occurred when this line executed because you are trying to Add NestedGroupMember.ToString() to member list that are now in a foreach loop, to solve error just create a temporarily variable for this Type just like tempGroup definition and then join them to main member list after foreach ends.
Please check this line :
member.Add(NestedGroupMember.ToString());
Maybe error occurred when this line executed because you are trying to Add NestedGroupMember.ToString() to member list that are now in a foreach loop, to solve error just create a temporarily variable for this Type just like tempGroup definition and then join them to main member list after foreach ends.
answered Nov 15 '18 at 9:43
MKHMKH
2571411
2571411
add a comment |
add a comment |
You are using foreach, but it doesnt allow you to modify the collection. BUT you can make a reversed for loop, like:
for (var i = list.Length - 1; i >= 0; i--
var item = list[i];
// TODO
That must work. Just replace all your foreach loops with collection modification with this reversed for.
add a comment |
You are using foreach, but it doesnt allow you to modify the collection. BUT you can make a reversed for loop, like:
for (var i = list.Length - 1; i >= 0; i--
var item = list[i];
// TODO
That must work. Just replace all your foreach loops with collection modification with this reversed for.
add a comment |
You are using foreach, but it doesnt allow you to modify the collection. BUT you can make a reversed for loop, like:
for (var i = list.Length - 1; i >= 0; i--
var item = list[i];
// TODO
That must work. Just replace all your foreach loops with collection modification with this reversed for.
You are using foreach, but it doesnt allow you to modify the collection. BUT you can make a reversed for loop, like:
for (var i = list.Length - 1; i >= 0; i--
var item = list[i];
// TODO
That must work. Just replace all your foreach loops with collection modification with this reversed for.
answered Nov 15 '18 at 19:13
Iv MisticosIv Misticos
197
197
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53316272%2fc-sharp-do-while-loop-for-a-list%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
You should not use
member.Add()insideforeachloop while still iteratingmembercollection contents. Consider read this issue: stackoverflow.com/questions/604831/….– Tetsuya Yamamoto
Nov 15 '18 at 9:34
1
What's the question?
– phuzi
Nov 15 '18 at 9:34
Possible duplicate of What is the best way to modify a list in a 'foreach' loop?
– Jevgeni Geurtsen
Nov 15 '18 at 9:34
2
Possible duplicate of Collection was modified; enumeration operation may not execute
– Tetsuya Yamamoto
Nov 15 '18 at 9:36
The question is how can I iterate through nested groups using foreach loop, but I can see that there are some post about possible duplicate, I will check them and search for an answer.
– varrimatrass
Nov 15 '18 at 9:52