1

Building a simple windows form, task is to read data contents from a file into a linq. Everything compiles which is fine, the issue is the output, this is wrapped in a foreach and as soon as information is displayed, instead of all data displayed at once, its one by one when you click ok.

It is weird because its not like that with the other code and it follows the same methodology. This is what I am doing.

Why is it displaying results one by one?

foreach (var info in linqData)
{
  MessageBox.Show(Convert.ToString(info.Count)+""+info.Line);
}
1
  • ... foreach is a loop construct. For every info item in the linqData collection it will execute the loop body. Commented Nov 12, 2018 at 3:57

2 Answers 2

5
StringBuilder sb=new StringBuilder();
foreach (var info in linqData)
{
 sb.Append(info.Count);
 sb.Append(";");
 sb.Append(info.Line);
 sb.Append(Environment.Newline); 
}
MessageBox.Show(sb.ToString());
Sign up to request clarification or add additional context in comments.

2 Comments

why do you use a string builder for this? why not to just string.Join(Environment.Newline, linqData.Select(info => $"{info.Count} {info.Line}"));?
For simplicity, but that also a fine solution.
0

Just to be clear, the problem is because you had a message box in a loop

You can simply this with Linq

var info = linqData.Select(x => $"{x.Count} {x.Line}");

MessageBox.Show(string.Join(Environment.NewLine,info);

or and StringBuilder

var sb = new StringBuilder();

foreach (var info in linqData)
  sb.AppendLine($"{xinfo.Count} {info.Line}");

MessageBox.Show(sb.ToString());

Additional Resources

Enumerable.Select Method

Projects each element of a sequence into a new form.

String.Join Method

Concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member.

$ - string interpolation (C# Reference)

The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolated expressions. When an interpolated string is resolved to a result string, items with interpolated expressions are replaced by the string representations of the expression results. This feature is available in C# 6 and later versions of the language.

StringBuilder Class

Represents a mutable string of characters.

StringBuilder.AppendLine Method

Appends the default line terminator, or a copy of a specified string and the default line terminator, to the end of this instance.

Environment.NewLine Property

Gets the newline string defined for this environment.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.