How to assign contents of List<String> to a RichTextBox? - c#

I've tried this:
richTextBoxResults.Text = listStrSessionIdLines.ToString();
...but get the List's ToString() representation (I guess that's what it is: "System.Collections.Generic.List`1[System.String]").
...and I've tried to try this:
listStrSessionIdLines.CopyTo(richTextBoxResults.Lines);
...but I get, "Argument Exception was unhandled. Destination array was not long enough. Check destIndex and length, and the array's lower bounds."
Does this mean I have to assign the RichTextBox a number of lines first, or...???

This works for me:
myRichTextBox.Lines = myList.ToArray();

Most classes in the BCL have a ToString() method.
When it comes to a List Of strSessionIdLines the ToString() tells you what type of object it is.
If you are casting for example an int to a string the int.ToString() will return its value, but if you do it on a array of integers int[].ToString it's ToString() method wont return eg a comma/linefeed separated string of values. As it appeared you expected.
This is why assigning the .ToArray to the .Lines property of the
RichTextBox or a loop (or aggregate) to concatenate the List Of String
into one string to suit the .Text property of the RichTextBox works.
One more tip I live by is when I need to call a method, eg String.Format I hover my mouse so that I can see what the method expects - expectsbeing the keyword. Then say the method wants a argument in the parameter thats of Type X, I declare type X and pass it in. Methods often have overloads, meaning that they can work with different parameters, so pressing up/down to scroll through them is also helpful in working out what is the most convenient in your situation. When you are passing in arguments to a method (in its parameter) type comma to refresh the tooltip indicating each arguments datatype.

Try This:
List<String> list = new List<String>();
list.Add("1");
list.Add("2");
richTextBox1.Lines = list.ToArray();

Using linq Aggregate which applies an accumulator function over a sequence.
richTextBoxResults.Text = listStrSessionIdLines.Aggregate((i, j) => i + j);

Related

String Splitting another string

I have used Splits in the past, but this one is a bit different for some reason, and I am not sure why...
Code:
string responceuptime = scripting.ReadUntilPrompt();
string[] suptime = responceuptime.Split('s');
UpTime.Text = suptime;
Error:
cannot implicitly convert type string[] to string
That is very basic thing and is very easy to figure out from the error message what is wrong actually.
The following line is the culprit by the way here:
UpTime.Text = suptime;
As suptime is of type string[] which is array while Text property is of type String. When assigning references to and from the type should be same otherwise we will see this error message which you just facing.
It's unclear from the above lines of code that what you are trying to achieve here, but you would need to assign single String object to Text, you cannot assign array or collection to single String object.
Hope it helps.
Your variable suptime is a string[] - an array of strings. While I don't know what Uptime.Text is, I'm guessing that it's looking for a single string, and that's why you're getting the compiler error that you are.
If you want to get the first string out of the array, then you could set it like so:
UpTime.Text = suptime[0];
The output of a call to String.Split is an array of strings (String[]). What your code does, here, is attempting to assign a String[] to a String variable, therefore the application is throwing an exception.
Hence, you must identify, within your array, the value you are looking for and picking the index that points to it (from 0 to suptime.Length - 1). For example:
UpTime.Text = suptime[0]; // first value of the array
UpTime.Text = suptime[2]; // third value of the array
UpTime.Text = suptime[suptime.Length - 1]; // last value of the array
If the result of your split is:
{"A" "Z" "11:57"}
and you want your UpTime.Text to be filled with something that looks like a time value, it's kinda obvious that the value you must pick is the third one.

Passing by reference to n-th element in C#

In C, if we have an array, we can pass it by reference to a function. We can also use simple addition of (n-1) to pass the reference starting from n-th element of the array like this:
char *strArr[5];
char *str1 = "I want that!\n";
char *str2 = "I want this!\n";
char *str3 = "I want those!\n";
char *str4 = "I want these!\n";
char *str5 = "I want them!\n";
strArr[0] = str1;
strArr[1] = str2;
strArr[2] = str3;
strArr[3] = str4;
strArr[4] = str5;
printPartially(strArr + 1, 4); //we can pass like this to start printing from 2nd element
....
void printPartially(char** strArrPart, char size){
int i;
for (i = 0; i < size; ++i)
printf(strArrPart[i]);
}
Resulting in these:
I want this!
I want those!
I want these!
I want them!
Process returned 0 (0x0) execution time : 0.006 s
Press any key to continue.
In C#, we can also pass reference to an object by ref (or, out). The object includes array, which is the whole array (or at least, this is how I suppose it works). But how are we to pass by reference to the n-th element of the array such that internal to the function, there is only string[] whose elements are one less than the original string[] without the need to create new array?
Must we use unsafe? I am looking for a solution (if possible) without unsafe
Edit:
I understand that we could pass Array in C# without ref keyword. Perhaps my question sounds quite misleading by mentioning ref when we talk about Array. The point why I put ref there, I should rather put it this way: is the ref keyword can be used, say, to pass the reference to n-th element of the array as much as C does other than passing reference to any object (without mentioning the n-th element or something alike)? My apology for any misunderstanding occurs by my question's phrasing.
The "safe" approach would be to pass an ArraySegment struct instead.
You can of course pass a pointer to a character using unsafe c#, but then you need to worry about buffer overruns.
Incidentally, an Array in C# is (usually) allocated on the heap, so passing it normally (without ref) doesn't mean copying the array- it's still a reference that is passed (just a new one).
Edit:
You won't be able to do it as you do in C in safe code.
A C# array (i.e. string[]) is derived from abstract type Array.
It is not only a simple memory block as it is in C.
So you can't send one of it's element's reference and start iterate from there.
But there are some solutions which will give you the same taste of course (without unsafe):
Like:
As #Chris mentioned you can use ArraySegment<T>.
As Array is also an IEnumerable<T> you can use .Skip and send the returned value. (but this will give you an IEnumerable<T> instead of an Array). But it will allow you iterate.
etc...
If the method should only read from the array, you can use linq:
string[] strings = {"str1", "str2", "str3", ...."str10"};
print(strings.Skip(1).Take(4).ToArray());
Your confusion is a very common one. The essential point is realizing that "reference types" and "passing by reference" (ref keyboard) are totally independent. In this specific case, since string[] is a reference type (as are all arrays), it means the object is not copied when you pass it around, hence you are always referring to the same object.
Modified Version of C# Code:
string[] strArr = new string[5];
strArr[0] = "I want that!\n";
strArr[1] = "I want this!\n";
strArr[2] = "I want those!\n";
strArr[3] = "I want these!\n";
strArr[4] = "I want them!\n";
printPartially(strArr.Skip(1).Take(4).ToArray());
void printPartially(string[] strArr)
{
foreach (string str in strArr)
{
Console.WriteLine(str);
}
}
Question is old, but maybe answer will be useful for someone.
As of C# 7.2 there are much more types to use in that case, ex. Span or Memory.
They allow exactly for the thing you mentioned in your question (and much more).
Here's great article about them
Currently, if you want to use them, remeber to add <LangVersion>7.2</LangVersion> in .csproj file of your project to use C# 7.2 features

After String.Reverse, a mistake occurs in ToString

When the application runs, the IDE tells me Input string is not in the correct format.
(Convert.ToInt32(_subStr.Reverse().ToString().Substring(4, _subStr.Length - 4))*1.6).ToString()
I don't know how the Reverse() can be exactly used here.
There is no Reverse method in the String class, so the method you're using is actually the Enumerable.Reverse extension method. This compiles because String implements IEnumerable<char>, but the result is not a string, it's another implementation of IEnumerable<char>. When you call ToString() on that, you get this: System.Linq.Enumerable+<ReverseIterator>d__a01[System.Char]`.
If you want to convert this IEnumerable<char> to a string, you can dot it like this:
string reversed = new string(_subStr.Reverse().ToArray());
(Convert.ToInt32(reversed.Substring(4, _subStr.Length - 4))*1.6).ToString()
Note, however, that it is not a correct way of reversing a string, it will fail in some cases due to Unicode surrogate pairs and combining characters. See here and there for explanations.
As the Reverse method is an extension of IEnumerable<T>, you get an IEnumerable<T> as result, and as that doesn't override the ToString method, you will get the original implementation from the Object class, that simply returns the type name of the object. Turn the IEnumerable<T> into an array, then you can create a string from it.
You should first get the part of the string that is digits, then reverse it. That way it will work, regardless of what characters you have in the rest of the string. Although using the Reverse extension doesn't work properly to reverse any string (as Thomas Levesque pointed out), it will work for a string with only digits:
(
Int32.Parse(
new String(_subStr.SubString(0, _subStr.Length - 4).Reverse().ToArray())
) * 1.6
).ToString();
the simplest approach would be:
string backwards = "sdrawkcab";
string reverse = "";
for(int i = backwards.Length-1; i >= 0; i--)
reverse += backwards[i];
The result is: reverse == "backwards".
then you can do:
reverse = (Convert.ToInt32(reverse) * 1.6).toString();
Your Piping approach string.Substring().Split().Last()... will very quickly lead to a memory bottleneck, if you loop through lines of text.
Also important to notice: strings are Immutable, therefor each iteration of the for loop we create a new string instance in the memory because of the += operator, this will give us less optimal memory efficieny compared to other, more efficient algorithms, this is an O(n2) algorithm.
for a more efficient implementation you can check:
https://stackoverflow.com/a/1009707/14473033

c# search arraylist problem

In my code I have an arraylist, called heart, which contains numbers from 1-13.
heart.Add("any");
for(int i = 0; i < 14; i++)
{
heart.Add(i);
}
As you can see it also contains "any" placed in the first element. When I use this code to get the all of the elements that has a value over 5 I get an error.
int store = heart.Cast<int>().Where(item => item > 5).Count().ToString();
I get the error "Specified cast is not valid" and that's because of the
"any" I have in the first element. Could anyone help me fix this?
It sounds like you just need the OfType method instead:
string store = heart.OfType<int>().Where(item => item > 5).Count().ToString();
OfType only returns values which are of the approriate type, ignoring others. See my Edulinq blog post on it for more information.
As Sven shows, you can also use the overload of Count which takes a predicate, to remove the Where call:
string store = heart.OfType<int>().Count(item => item > 5).ToString();
(I've changed the variable type given that you're calling ToString at the end... again, you may want to think about this decision. It depends on how you're using it of course.)
However, I'd strongly advise you to use a strongly-typed collection instead of ArrayList. Think about what the collection is meant to hold - it seems odd to hold both strings and integers. What are you trying to do with it?
Use this instead:
int count = heart.OfType<int>().Count(item => item > 5);
OfType will filter the list and return only those elements that are the correct type, rather than Cast which tries to cast all elements.
You can't cast the word "any" to an integer, that's pretty straight forward.
We'd have to know exactly what your trying to do with here, and how the array is used to really give a good recommendation.
Since you're using int and you wanted values of 1-13, may I suggest you use an int value of 0 to represent 'any'?
You could do
Int store = heart.GetRange(1, heart.Count - 1).Cast<int>().Where(item => item > 5).Count().ToString();

How to use an enumeration in an XNA ContentReader?

For instance, I was thinking of replacing this:
var.StringAttribute = input.ReadString();
With something like this:
var.EnumAttribute = input.ReadExternalReference<EnumName>();
However this doesn't work quite right. And ideas on how to get input to read a custom enumeration?
ReadExternalReference Reads a link to an external file - that's not what you want to do.
If I understand you correctly, you want to read a string, and parse it as an enum.
Try this:
string value = input.ReadString();
var.EnumAttribute = Enum.Parse(typeof(EnumName), value);
Note that this will work for both numbers (anything within the range of the enum's underlying type - typically Int32) and string values, but will throw an exception for invalid values.

Categories

Resources