471,355 Members | 1,618 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,355 software developers and data experts.

String foreach problem

Hi guys, i hace a question

i have a datagrid

col1 col2
-----------------
D text0
text1
text2
D text3
D text4

i need to do a foreach and everywhere where's a "D" in col1 to add the
value of col2 into a string, so the final string would be "text0" +
"," + "text3" + "," + "text4";

for example:

string Uvjet()
{
foreach (DataRow red in dt.Rows)
{
if (red["col1"].ToString() == "D")
{
string uvjet = red["col2"].ToString() + ",";
}
}
return uvjet;
}
...only this fills the string "uvjet" only with one value....and i want
it to be finally filled with all necessary values, like:
"text0" + "," + "text3" + "," + "text4"

if you have any ideas, please help...
THANX!

Jul 9 '07 #1
29 1780


"ApeX" <mm****@gmail.comwrote in message
news:11**********************@o61g2000hsh.googlegr oups.com...
string Uvjet()
{
foreach (DataRow red in dt.Rows)
{
if (red["col1"].ToString() == "D")
{
string uvjet = red["col2"].ToString() + ",";
}
}
return uvjet;
}
..only this fills the string "uvjet" only with one value....and i want
it to be finally filled with all necessary values, like:
"text0" + "," + "text3" + "," + "text4"

if you have any ideas, please help...
THANX!
From what I see, that code won't even compile...

try:

string Uvjet()
{
string uvjet = string.Empty;
foreach (DataRow red in dt) {
if (red["col1"].ToString() == "D") {
if (uvjet != string.Empty) uvjet += ";";
uvjet = red["col2"].ToString();
}
}
return uvjet;
}

Note: The above is NOT functionally equivalent to what you posted earlier.
This ONLY adds a semi-colon on iterations after the first iteration (so you
won't have a single entry with a semi-colon at the end of the string).

Also note, I haven't tested it so it may not compile either :D

HTH,
Mythran
Jul 9 '07 #2
ApeX wrote:
Hi guys, i hace a question

i have a datagrid

col1 col2
-----------------
D text0
text1
text2
D text3
D text4

i need to do a foreach and everywhere where's a "D" in col1 to add the
value of col2 into a string, so the final string would be "text0" +
"," + "text3" + "," + "text4";

for example:

string Uvjet()
{
foreach (DataRow red in dt.Rows)
{
if (red["col1"].ToString() == "D")
{
string uvjet = red["col2"].ToString() + ",";
}
}
return uvjet;
}
..only this fills the string "uvjet" only with one value....and i want
it to be finally filled with all necessary values, like:
"text0" + "," + "text3" + "," + "text4"

if you have any ideas, please help...
THANX!
As Mythran mentioned, your code will not even compile. As you have
declared the uvjet string inside the if statement, that's the scope of
the variable, and you can't use it outside of it's scope.

If you correct the code by declaring the string outside the loop, you
are still just assigning the value to the string, that means that you
will be replacing the value from any previous row. You have to
concatenate the strings.

This is however a good example where concatenating strings is a bad
idea. As strings are immutable in .NET, you will be creating a new
string for every concatenation, copying the previous string data into
the new string. That means that you will be moving more and more data
for every additional value that you add to the string. The amount of
memory used is exponetially proportional to the number of strings added.

The solution is a StringBuilder.

Whenever you are concatenating string, and you don't know beforehand
exactly how many strings there will be, it's better to use a StringBuilder.

StringBuilder builder = new StringBuilder();
foreach (DataRow red in dt.Rows) {
if (red["col1"].ToString() == "D") {
if (builder.Length 0) {
builder.Append(',');
}
builder.Append(red["col2"].ToString());
}
}
return builder.ToString();

Note that this code does not add an extra comma at the end of the
string, unlike what your original code would have done.

--
Göran Andersson
_____
http://www.guffa.com
Jul 9 '07 #3
On Mon, 09 Jul 2007 15:48:49 -0700, ApeX <mm****@gmail.comwrote:
Hi guys, i hace a question

i have a datagrid
Your code appears to be using a DataTable, not a DataGrid. There's a
difference.
col1 col2
-----------------
D text0
text1
text2
D text3
D text4

i need to do a foreach and everywhere where's a "D" in col1 to add the
value of col2 into a string, so the final string would be "text0" +
"," + "text3" + "," + "text4";
So, you only want commas between the fields, and not one at the end?

While Mythran's reply is wrong in at least a couple of ways, it does offer
one insight that should be useful to you: initialize a string to the empty
string, and then append text with each iteration as appropriate. He is
also correct that your code doesn't compile (since you use "uvjet" outside
of the code block in which it's declared).

So:

string Uvjet()
{
string uvjet = "";
foreach (DataRow red in dt.Rows)
{
if (red["col1"].ToString() == "D")
{
if (uvjet != "")
{
uvjet += ",";
}
uvjet += red["col2"].ToString();
}
}
return uvjet;
}

If you like, you could use a StringBuilder instance with the Append()
method instead of using the + concatenation operator with the String class.

Pete
Jul 9 '07 #4
On Mon, 09 Jul 2007 16:12:20 -0700, Mythran <ki********@hotmail.comwrote:
From what I see, that code won't even compile...
Just FYI...

I think your code will compile, but it has some problems:
try:

string Uvjet()
{
string uvjet = string.Empty;
foreach (DataRow red in dt) {
if (red["col1"].ToString() == "D") {
if (uvjet != string.Empty) uvjet += ";";
He wanted commas, not semicolons.
uvjet = red["col2"].ToString();
This line simply replaces "uvjet" with a new string instance. No
concatenation.
}
}
return uvjet;
}
Pete
Jul 9 '07 #5
A StringBuilder is used to build a string. I can't imagine needing a string
so long that using a StringBuilder instead of creating new strings would be
significant.
Jul 10 '07 #6
On Mon, 09 Jul 2007 17:42:42 -0700, Mark Wilden <mw*****@communitymtm.com>
wrote:
A StringBuilder is used to build a string.
Which is, in fact, what the OP is trying to do.
I can't imagine needing a string
so long that using a StringBuilder instead of creating new strings would
be
significant.
Ever? Then why does the StringBuilder class exist?

Seriously though: you and I have no idea what the length of the string
is. It could be hundreds of kilobytes or larger for all we know.

It may well be that the OP is dealing with just a few rows of data and
thus concatenation is fine. But it is just as true that for all we know
he's got thousands of rows of data, and that using a StringBuilder would
in fact be noticeably better.

Pete
Jul 10 '07 #7
Mark Wilden wrote:
A StringBuilder is used to build a string. I can't imagine needing a string
so long that using a StringBuilder instead of creating new strings would be
significant.
How about this for a real world example:

http://www.codeproject.com/script/co...00&tid=1519247

--
Göran Andersson
_____
http://www.guffa.com
Jul 10 '07 #8
On Jul 10, 1:42 am, "Mark Wilden" <mwil...@communitymtm.comwrote:
A StringBuilder is used to build a string. I can't imagine needing a string
so long that using a StringBuilder instead of creating new strings would be
significant.
See http://pobox.com/~skeet/csharp/stringbuilder.html

The length of the string that isn't the only significant factor - it's
the amount of redundant data which needs copying. Building up a 50K
string one character at a time (using string concatenation) is painful
- but concatenating two 500K strings is quick.

Jon

Jul 10 '07 #9


"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
On Mon, 09 Jul 2007 16:12:20 -0700, Mythran <ki********@hotmail.comwrote:
From what I see, that code won't even compile...
Just FYI...

I think your code will compile, but it has some problems:
try:

string Uvjet()
{
string uvjet = string.Empty;
foreach (DataRow red in dt) {
if (red["col1"].ToString() == "D") {
if (uvjet != string.Empty) uvjet += ";";
He wanted commas, not semicolons.
uvjet = red["col2"].ToString();
This line simply replaces "uvjet" with a new string instance. No
concatenation.

whoops, I originally had += there :P Oh well....that's why the disclaimer
was in there... :)

Kip

Jul 10 '07 #10
"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
Seriously though: you and I have no idea what the length of the string
is. It could be hundreds of kilobytes or larger for all we know.
It may well be that the OP is dealing with just a few rows of data and
thus concatenation is fine. But it is just as true that for all we know
he's got thousands of rows of data, and that using a StringBuilder would
in fact be noticeably better.
The poster is using a DataGrid. It's not good practice to put a large number
of items in a DataGrid. What would the user do with thousands of rows?.

Jul 11 '07 #11
"Göran Andersson" <gu***@guffa.comwrote in message
news:Oi**************@TK2MSFTNGP03.phx.gbl...
Mark Wilden wrote:
>A StringBuilder is used to build a string. I can't imagine needing a
string so long that using a StringBuilder instead of creating new strings
would be significant.

How about this for a real world example:

http://www.codeproject.com/script/co...00&tid=1519247
OK, when you're creating a string from all the bytes of a 120K file, I can
see using StringBuilder.

///ark
Jul 11 '07 #12


"Mark Wilden" <mw*****@communitymtm.comwrote in message
news:Of**************@TK2MSFTNGP05.phx.gbl...
"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
>Seriously though: you and I have no idea what the length of the string
is. It could be hundreds of kilobytes or larger for all we know.
It may well be that the OP is dealing with just a few rows of data and
thus concatenation is fine. But it is just as true that for all we know
he's got thousands of rows of data, and that using a StringBuilder would
in fact be noticeably better.

The poster is using a DataGrid. It's not good practice to put a large
number of items in a DataGrid. What would the user do with thousands of
rows?.
The poster stated he/she/it is using a DataGrid, but the code shows a
DataTable with DataRow's, so we are assuming he/she/it meant DataSet.

:)

Mythran
Jul 11 '07 #13
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:11**********************@o61g2000hsh.googlegr oups.com...
>
See http://pobox.com/~skeet/csharp/stringbuilder.html
See it? I've practically memorized it!
The length of the string that isn't the only significant factor - it's
the amount of redundant data which needs copying. Building up a 50K
string one character at a time (using string concatenation) is painful
- but concatenating two 500K strings is quick.
My point was that I couldn't imagine building up a 50K string one character
at a time. Goran posted an example of doing something like that, but I'd
still say that was very rare.

At least your article has disabused people of the notion that concatentation
should always be done using StringBuilder. However, a lot of folks still
think that StringBuilder should be used whenever concatenating in a loop,
and I think this is premature optimization most of the time. In general, I'd
call long strings (thousands of characters) a code smell.

For example, Goran's example was about "showing users a string
representation of a 120Kb file in Hex-format within a Windows forms
textbox." How useful would that actually be to anyone? I'm not saying it's
impossible; just that I'm doubtful.

///ark
Jul 11 '07 #14
"Mythran" <ki********@hotmail.comwrote in message
news:18**********************************@microsof t.com...
>
The poster stated he/she/it is using a DataGrid, but the code shows a
DataTable with DataRow's, so we are assuming he/she/it meant DataSet.
That makes it more likely that a long string would be generated from the
rows, but I'd still like to know what is planned to be done with that
string.

///ark
Jul 11 '07 #15
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP********************@msnews.microsoft.com.. .
>
You wouldn't normally do exactly that, but I've seen plenty of real
world examples where people *have* built up a very large string line by
line. For instance, here's a really bad way of reading a text file:
This is really my point. The advice against using + for concatenating
strings is usually accompanied by a very bad reason for concatenating in the
first place.
I use a StringBuilder when I don't have concrete guarantees about the
number of iterations.
I don't require a concrete guarantee - just some idea of the number of
iterations. If there are a lot of iterations, StringBuilder is the best
choice - agreed. I'm just questioning how many times that happens. My
definition of "a lot" is the same as yours, I suspect - where performance
degradation is noticeable.
Long strings can be useful quite often. Not all the time, but quite often.
"Quite often" is obviously subjective. All I can say from my experience is
that long strings are rarely useful (as in, I might need to use them once a
year). My suspicion (and it's only that) is that many (there's that word
again) uses of long strings are incorrect (which goes for the examples I've
seen so far here).
>Why introduce an O(n^2) way of building them up when an O(n) way
exists which is very straightforward to use?
Because + is easier to read than a method call. In the example that I saw
most recently, there were five lines of code just to put a string together -
because the programmer was afraid of +.

///ark
Jul 11 '07 #16
Mark Wilden <mw*****@communitymtm.comwrote:
You wouldn't normally do exactly that, but I've seen plenty of real
world examples where people *have* built up a very large string line by
line. For instance, here's a really bad way of reading a text file:

This is really my point. The advice against using + for concatenating
strings is usually accompanied by a very bad reason for concatenating in the
first place.
I didn't say that the reason for reading the text file line by line was
bad. For instance, there might have been a good reason to have the
whole thing in memory at a time as a string, having prepended the line
number to each line.

The only really bad thing about the example was using concatenation.
I use a StringBuilder when I don't have concrete guarantees about the
number of iterations.

I don't require a concrete guarantee - just some idea of the number of
iterations. If there are a lot of iterations, StringBuilder is the best
choice - agreed. I'm just questioning how many times that happens. My
definition of "a lot" is the same as yours, I suspect - where performance
degradation is noticeable.
All I can say is that my experience on the groups is that it's far from
unheard of for the degredation to be noticeable.
Long strings can be useful quite often. Not all the time, but quite often.

"Quite often" is obviously subjective. All I can say from my experience is
that long strings are rarely useful (as in, I might need to use them once a
year). My suspicion (and it's only that) is that many (there's that word
again) uses of long strings are incorrect (which goes for the examples I've
seen so far here).
"Incorrect" sounds very concrete to me. If there's more than one way of
achieving an overall goal, what makes one way "incorrect"?
Why introduce an O(n^2) way of building them up when an O(n) way
exists which is very straightforward to use?

Because + is easier to read than a method call. In the example that I saw
most recently, there were five lines of code just to put a string together -
because the programmer was afraid of +.
It's certainly abused - but so is string concatenation. In both cases
it's usually because of ignorance.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jul 11 '07 #17
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP*********************@msnews.microsoft.com. ..
>
I didn't say that the reason for reading the text file line by line was
bad. For instance, there might have been a good reason to have the
whole thing in memory at a time as a string, having prepended the line
number to each line.
Oh, OK. You mentioned ReadToEnd, which I'd say was a better way than
concatenation, by whatever means.
All I can say is that my experience on the groups is that it's far from
unheard of for the degredation to be noticeable.
I agree. What I'm trying to say is that sometimes we need to take a step
back and ask whether concatenating large numbers of strings is the real
problem - not the method of accomplishing it.
"Incorrect" sounds very concrete to me. If there's more than one way of
achieving an overall goal, what makes one way "incorrect"?
Again, I'm saying that it appears to me that the goal is what's incorrect.
For example, you should use Append to turn a binary file into hex digits
instead of +. But should you display a binary file in a textbox in the first
place? That's why I call long strings a "smell." Not prima facie incorrect,
but often incorrect.

///ark
Jul 11 '07 #18
On Wed, 11 Jul 2007 10:32:41 -0700, Mark Wilden <mw*****@communitymtm.com>
wrote:
The poster is using a DataGrid. It's not good practice to put a large
number
of items in a DataGrid. What would the user do with thousands of rows?.
Well, as has been pointed out, it seems safer to assume that the OP
misstated, and they are in fact using a DataSet, not DataGrid. But
whether he is or not, my point is that your statement didn't restrict
itself to a DataGrid, and as a more general statement I found it lacking.

You didn't write "I can't imagine needing a string created from a DataGrid
that is so long that using a StringBuilder instead of creating new strings
would be significant".

You did write "I can't imagine needing a string so long that using a
StringBuilder instead of creating new strings would be significant".

There's a world of difference between the two statements, and my point is
that there certainly are scenarios in which a StringBuilder makes a LOT of
sense for concatenating strings.

Pete
Jul 11 '07 #19
Mark Wilden wrote:
I don't require a concrete guarantee - just some idea of the number of
iterations. If there are a lot of iterations, StringBuilder is the best
choice - agreed. I'm just questioning how many times that happens. My
definition of "a lot" is the same as yours, I suspect - where performance
degradation is noticeable.
It's not only a question of performance, but also about scalability.
Systems tend to grow over time, so many times it's better to choose a
method that scales well rather than a method that performs well when
testing with a certain amount of data.

If you have ten strings, using Concat might be faster than using a
StringBuilder. Even if you have 20 string, perhaps even 30. After that
it starts getting bad, and fast. Every single additional string means
that you use twice as much memory to concatenate them.

As long as you don't have much data, performance isn't really a problem
anyway. It's when the data starts to grow that it shows if you are able
to write scalable code.

--
Göran Andersson
_____
http://www.guffa.com
Jul 11 '07 #20
On Wed, 11 Jul 2007 15:40:06 -0700, Göran Andersson <gu***@guffa.com>
wrote:
[...]
If you have ten strings, using Concat might be faster than using a
StringBuilder. Even if you have 20 string, perhaps even 30. After that
it starts getting bad, and fast. Every single additional string means
that you use twice as much memory to concatenate them.

As long as you don't have much data, performance isn't really a problem
anyway. It's when the data starts to grow that it shows if you are able
to write scalable code.
Exactly. And just in case Göran's point wasn't clear enough:

If you have so few strings to concatenate that concatention is faster than
using StringBuilder, then _neither_ implementation is likely to be of any
significance with respect to performance.

It is only when the number of strings gets large that the performance
matters, and StringBuilder will always be better in those scenarios.

Pete
Jul 11 '07 #21
"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
>
It is only when the number of strings gets large that the performance
matters, and StringBuilder will always be better in those scenarios.
I agree, but that doesn't have the slightest thing to do with what I've been
saying.

///ark
Jul 11 '07 #22
On Wed, 11 Jul 2007 16:13:42 -0700, Mark Wilden <mw*****@communitymtm.com>
wrote:
>It is only when the number of strings gets large that the performance
matters, and StringBuilder will always be better in those scenarios.

I agree, but that doesn't have the slightest thing to do with what I've
been
saying.
Not the slightest? Surely it has at least a little to do with what
"you've been saying". In particular, the post to which I replied (and the
only one I've had a comment on) claimed that no one would ever have to
concatenate a string so long that StringBuilder would be better than
concatenation.

That sure seems to be directly relevant to what Göran wrote, as well as my
reply to him to which you replied.

In any case, we might quibble about just _how_ relevant the two are, but
it seems obviously wrong that it "doesn't have the slightest thing" in
relevance.

Pete
Jul 11 '07 #23
Pete, I completely agree that when the number of strings get large,
StringBuilder is better than +. I've never said otherwise. Telling me
that is preaching to the choir.

My point has been to question the need to concatenate large numbers of
strings. At first, I couldn't imagine a good reason to do so.
Actually, I still can't, since I haven't seen a good example yet. But
I won't deny there are cases where that need exists (even if no one
can think of one easily).

I'll say it just one last time: I think concatenating a large number
of strings represents a "code smell." Nothing to do with
StringBuilder.

///ark

Jul 12 '07 #24
ma**@mwilden.com wrote:
Pete, I completely agree that when the number of strings get large,
StringBuilder is better than +. I've never said otherwise. Telling me
that is preaching to the choir.

My point has been to question the need to concatenate large numbers of
strings. At first, I couldn't imagine a good reason to do so.
Actually, I still can't, since I haven't seen a good example yet. But
I won't deny there are cases where that need exists (even if no one
can think of one easily).

I'll say it just one last time: I think concatenating a large number
of strings represents a "code smell." Nothing to do with
StringBuilder.

///ark
An example of a very common use, is a web page. When ASP.NET renders a
web page, the html code for each element of the page is put into a
single large string. This is often hundreds of strings, perhaps
thousands, and the resulting string may be several kilobytes.

Of course it's done using a StringBuilder.

--
Göran Andersson
_____
http://www.guffa.com
Jul 12 '07 #25
"Göran Andersson" <gu***@guffa.comwrote in message
news:ek**************@TK2MSFTNGP02.phx.gbl...
>
An example of a very common use, is a web page. When ASP.NET renders a web
page, the html code for each element of the page is put into a single
large string.
Example accepted. :)

However, this is not common. Not many of us write our own web framework, so
I still stick to "rare."

///ark
Jul 12 '07 #26
On Thu, 12 Jul 2007 10:56:56 -0700, "Mark Wilden"
<mw*****@communitymtm.comwrote:
>"Göran Andersson" <gu***@guffa.comwrote in message
news:ek**************@TK2MSFTNGP02.phx.gbl...
>>
An example of a very common use, is a web page. When ASP.NET renders a web
page, the html code for each element of the page is put into a single
large string.

Example accepted. :)

However, this is not common. Not many of us write our own web framework, so
I still stick to "rare."

///ark
Hi Mark

Another example would be building a data file with, say, daily share
dealing information. Customer details and their share dealings for a
day are processed at close of business and submitted to an external
company for processing on their systems to check whether the deals are
valid and comply with money laundering regulations, for instance.

The data files may contain transactions by thousands of customers and
an unspecified but numerous number of deals. Often the legacy systems
still in use are not setup to process this information real-time and
so the datafile is built and transferred at close of business. Once
processed the results are returned using a similar process.

There are many other instances where business requires bulk processing
of strings.

Steve
Jul 12 '07 #27
"steve.falzon@ noonbay.co.uk" <nospampleasewrote in message
news:dd********************************@4ax.com...
>
Another example would be building a data file with, say, daily share
dealing information.
Why not just write to the file directly?

///ark
Jul 12 '07 #28
Mark Wilden wrote:
"Göran Andersson" <gu***@guffa.comwrote in message
news:ek**************@TK2MSFTNGP02.phx.gbl...
>An example of a very common use, is a web page. When ASP.NET renders a web
page, the html code for each element of the page is put into a single
large string.

Example accepted. :)

However, this is not common. Not many of us write our own web framework, so
I still stick to "rare."
What do you accept the example as, if you don't accept it as an example?
Doesn't it count because the guys at microsoft wrote the code?

It's used millions of time every day, I wouldn't call that "rare"...

--
Göran Andersson
_____
http://www.guffa.com
Jul 12 '07 #29
"Göran Andersson" <gu***@guffa.comwrote in message
news:uu*************@TK2MSFTNGP03.phx.gbl...
What do you accept the example as, if you don't accept it as an example?
It's an example of a legitimate (IMO) reason for creating long strings.
It's used millions of time every day, I wouldn't call that "rare"...
This is a programmer's forum. I think it's rare in programming to create
long strings. Only Microsoft creates the long strings in your example.

///ark
Jul 12 '07 #30

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by Caroline | last post: by
17 posts views Thread by Chad Myers | last post: by
32 posts views Thread by tshad | last post: by
5 posts views Thread by SMichal | last post: by
reply views Thread by XIAOLAOHU | last post: by

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.