473,796 Members | 2,586 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to remove a item from System.Collecti ons.Generic.Lis t in a loo

Hi,

Following code does not work. (it will crash.)-- I think the reason is that
I cannot modify list (call remove) in foreach. But I don't know what I can
do.

-----------------------------------------------------------------------
List<stringarst r = new List<string>();
//init data
for (int i = 0; i < 30; ++i)
{
arstr.Add(i.ToS tring());
}

//go through items one by one
//and remove item start with 1 e.g. 1, 10,11...,100...
foreach (string str in arstr)
{
if (str.Length 0 && str[0] == '1')
{
arstr.Remove(st r);
}
}

//print the result
foreach (string str in arstr)
{
Console.WriteLi ne(str);
}

Best Regards,
Michael zhang
Jun 27 '07 #1
4 5539
Hi zhanglr,

Make a new list of removing objects and remove them after the loop (you cannot
modify the list of foreach during its execution).
But, it may be better to make the list of passed objects instead of deleted.

Kind Regards, Alex Meleta
[TechBlog] http://devkids.blogspot.com

zHi,
z>
zFollowing code does not work. (it will crash.)-- I think the reason
zis that I cannot modify list (call remove) in foreach. But I don't
zknow what I can do.
z>
z---------------------------------------------------------------------
z--
zList<stringars tr = new List<string>();
z//init data
zfor (int i = 0; i < 30; ++i)
z{
zarstr.Add(i.To String());
z}
z//go through items one by one
z//and remove item start with 1 e.g. 1, 10,11...,100...
zforeach (string str in arstr)
z{
zif (str.Length 0 && str[0] == '1')
z{
zarstr.Remove(s tr);
z}
z}
z//print the result
zforeach (string str in arstr)
z{
zConsole.WriteL ine(str);
z}
zBest Regards,
zMichael zhang
Jun 27 '07 #2
Hi,

First of all, thank you for your reply.

I just wonder whether there is any better way. E.g. in C++ we are able to
call std::remove_if or list::erase (the return value is iterator so I am able
to continue.) I think maybe MS has provided the samilar functions. I just
haven't found it yet.

At the end, thanks for your reply again.

Best Regards
Michael zhang

"Alex Meleta" wrote:
Hi zhanglr,

Make a new list of removing objects and remove them after the loop (you cannot
modify the list of foreach during its execution).
But, it may be better to make the list of passed objects instead of deleted.

Kind Regards, Alex Meleta
[TechBlog] http://devkids.blogspot.com

zHi,
z>
zFollowing code does not work. (it will crash.)-- I think the reason
zis that I cannot modify list (call remove) in foreach. But I don't
zknow what I can do.
z>
z---------------------------------------------------------------------
z--
zList<stringars tr = new List<string>();
z//init data
zfor (int i = 0; i < 30; ++i)
z{
zarstr.Add(i.To String());
z}
z//go through items one by one
z//and remove item start with 1 e.g. 1, 10,11...,100...
zforeach (string str in arstr)
z{
zif (str.Length 0 && str[0] == '1')
z{
zarstr.Remove(s tr);
z}
z}
z//print the result
zforeach (string str in arstr)
z{
zConsole.WriteL ine(str);
z}
zBest Regards,
zMichael zhang
Jun 27 '07 #3
Hi zhanglr,

Because you will have two arrays: one as a source (as immutable) and second
is filtered. Safe way.

And yes, MS provides similar functions: you can also use e.g. list.RemoveAll( delegate(int
value) { return <some_case_to_r eturn_bool>; }) to clear particular values
(see also other .Remove<somefun ctions of list)

Kind Regards, Alex Meleta
[TechBlog] http://devkids.blogspot.com

zHi,
z>
zFirst of all, thank you for your reply.
z>
zI just wonder whether there is any better way. E.g. in C++ we are
zable to call std::remove_if or list::erase (the return value is
ziterator so I am able to continue.) I think maybe MS has provided the
zsamilar functions. I just haven't found it yet.
z>
zAt the end, thanks for your reply again.
z>
zBest Regards
zMichael zhang
z"Alex Meleta" wrote:
z>
>Hi zhanglr,

Make a new list of removing objects and remove them after the loop
(you cannot modify the list of foreach during its execution). But, it
may be better to make the list of passed objects instead of deleted.

Kind Regards, Alex Meleta
[TechBlog] http://devkids.blogspot.com
zHi,
z>
zFollowing code does not work. (it will crash.)-- I think the
reason
zis that I cannot modify list (call remove) in foreach. But I don't
zknow what I can do.
z>
z>
---------------------------------------------------------------------
z--
zList<stringar str = new List<string>();
z//init data
zfor (int i = 0; i < 30; ++i)
z{
zarstr.Add(i.T oString());
z}
z//go through items one by one
z//and remove item start with 1 e.g. 1, 10,11...,100...
zforeach (string str in arstr)
z{
zif (str.Length 0 && str[0] == '1')
z{
zarstr.Remove( str);
z}
z}
z//print the result
zforeach (string str in arstr)
z{
zConsole.Write Line(str);
z}
zBest Regards,
zMichael zhang

Jun 27 '07 #4
Hi,

Thank you so much.

Best Regards,
Michael zhang

"Alex Meleta" wrote:
Hi zhanglr,

Because you will have two arrays: one as a source (as immutable) and second
is filtered. Safe way.

And yes, MS provides similar functions: you can also use e.g. list.RemoveAll( delegate(int
value) { return <some_case_to_r eturn_bool>; }) to clear particular values
(see also other .Remove<somefun ctions of list)

Kind Regards, Alex Meleta
[TechBlog] http://devkids.blogspot.com

zHi,
z>
zFirst of all, thank you for your reply.
z>
zI just wonder whether there is any better way. E.g. in C++ we are
zable to call std::remove_if or list::erase (the return value is
ziterator so I am able to continue.) I think maybe MS has provided the
zsamilar functions. I just haven't found it yet.
z>
zAt the end, thanks for your reply again.
z>
zBest Regards
zMichael zhang
z"Alex Meleta" wrote:
z>
Hi zhanglr,

Make a new list of removing objects and remove them after the loop
(you cannot modify the list of foreach during its execution). But, it
may be better to make the list of passed objects instead of deleted.

Kind Regards, Alex Meleta
[TechBlog] http://devkids.blogspot.com
zHi,
z>
zFollowing code does not work. (it will crash.)-- I think the
reason
zis that I cannot modify list (call remove) in foreach. But I don't
zknow what I can do.
z>
z>
---------------------------------------------------------------------
z--
zList<stringars tr = new List<string>();
z//init data
zfor (int i = 0; i < 30; ++i)
z{
zarstr.Add(i.To String());
z}
z//go through items one by one
z//and remove item start with 1 e.g. 1, 10,11...,100...
zforeach (string str in arstr)
z{
zif (str.Length 0 && str[0] == '1')
z{
zarstr.Remove(s tr);
z}
z}
z//print the result
zforeach (string str in arstr)
z{
zConsole.WriteL ine(str);
z}
zBest Regards,
zMichael zhang


Jun 27 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
15183
by: Abhi | last post by:
In the following hypothetical example I want to build a generic list of unique string items. How should I implement the pred function so that it returns true/false if target string exists in the generic list...is not clear to me. Any suggestions? System.Collections.Generic.List<string> list = new System.Collections.Generic.List<string>(); foreach(string s in myAnotherArray)
2
3312
by: ljlevend | last post by:
I've noticed that in VS.NET 2.0 Beta 1 that none of the methods in System.Collections.Generic.List are overridable. In my app I currently have over 50 strongly typed ArrayLists that inherit from System.Collections.ArrayList. Each of these types raise strongly typed events for when items are added and removed (e.g., AddingItem, AddedItem, CollectionChanged, etc.). One of my hopes for v2.0 was to create a single generic List that replaces...
3
5545
by: snesbit | last post by:
I have a structure called SearchAreaListItem. The structure has some properties. The application implements this as a collection.generic.list(of SearchAreaListItem) I load the collection up item at a time stuffing values into the item then adding the item to the collection.
3
2102
by: Varangian | last post by:
Hello, there I have a problem with regards to System.Collections.Generic.List<T> I need to pass a class with implements an interface - TestClass : IPerson I put this class in a List<TestClass> = new List<TestClass>(); then I pass this List<TestClass> to a function which takes an argument List<IPerson> person
2
2065
by: newscorrespondent | last post by:
I have a list declared: public System.Collections.Generic.SortedList<int, System.Collections.Generic.List<MTGTracer ActiveList = new SortedList<int,List<MTGTracer>>(); The key is an integer and the value is a list of MTGTracer. The documentation states:
0
1162
by: Susan | last post by:
I have an issue with the System.Collections.Generic.List that I can't find anywhere else... My website suddenly starts giving off System.IndexOutOfRangeException: Index was outside the bounds of the array. errors in a spot that I cannot figure out the problem. It will work all day, then suddenly start giving off the error, which makes quite a bit fail. The error (System.IndexOutOfRangeException: Index was outside the bounds of the...
1
2627
by: Kuldeep | last post by:
Framework: Visual Studio 2005, ASP.NET Programing Language: C#.NET I am using a Generic List Collection to fetch a particular master data from the database. Once collected, I use this Collection to bind it to a DataGrid. Now that I am using a Generic List Collection to populate the DataGrid, say another user would insert a new record on to the same master data from a different machine, the updated data (along with the lastest inserted...
2
7364
by: Fred Heida | last post by:
Hi, i'm trying to (using managed C++) implment the IEnumerable<Tinterface on my class.. but have a problem with the 2 GetEnumerator method required.... what i have done is... generic<typename T> public ref class SetOfProxy : public System::Collections::Generic::IEnumerable<T>
0
1339
by: DR | last post by:
System.Collections.Generic.List<intmyList = new System.Collections.Generic.List<int>(100); Does this preallocate 100 integers? Also, is there any way to preallocate an array of objects all at once? MyOb al= new MyOb; for (int z = 0; z < nCount; z++)
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9535
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10465
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10242
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9061
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6800
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4127
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2931
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.