Reputation:
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);
}
Upvotes: 1
Views: 136
Reputation: 81493
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
Projects each element of a sequence into a new form.
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.
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.
Gets the newline string defined for this environment.
Upvotes: 0
Reputation: 665
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());
Upvotes: 5