This question already has answers here:
What is the .NET equivalent of PHP var_dump?
(5 answers)
Closed 6 years ago.
I need to dump the content of arrays or objects and I am interested to know if in C# we have something like PHP instruction var_dump.
The objective is to not build a loop to use every property or content of array or object and print with Console.WriteLine.
The closest thing would probably be string.Join:
Console.WriteLine(string.Join(", ", myEnumOfObjects));
It would not automatically include "every property or content of array or object" into the output, though - if you want that to happen, you need to override the ToString method of the object being printed:
class MyObject {
public string Name {get;set;}
public DateTime Dob {get;set;}
public override string ToString() {
return string.Format("{0} - {1}", Name, Dob);
}
}
I think there aren't direct equivalent of var_dump php function.
You must use reflection to write an equivalent function.
If you search in web, you can easily find code which do it.
For example : http://ruuddottech.blogspot.fr/2009/07/php-vardump-method-for-c.html
When you insert a break point you can easily view the contents of an array by hovering your mouse over it.
or any of these:
You are probably using Console.WriteLine for printing the array.
int[] array = new int[] { 1, 2, 3 };
foreach(var item in array)
{
Console.WriteLine(item.ToString());
}
If you don't want to have every item on a separate line use Console.Write:
int[] array = new int[] { 1, 2, 3 };
foreach(var item in array)
{
Console.Write(item.ToString());
}
or string.Join (in .NET Framework 4 or later):
int[] array = new int[] { 1, 2, 3 };
Console.WriteLine(string.Join(",", array));
from this question: How to print contents of array horizontally?
I know you want to avoid loop, but if its just for the sake of writing multiple lines of code, below is a one liner loop that could allow you to print data with single line for Objects extend ForEach Method
List<string> strings=new List<string>{"a","b","c"};//declare one
strings.ForEach(x => Console.WriteLine(x));//single line loop...for printing and is easier to write
Related
This question already has answers here:
What is the fastest way of converting an array of floats to string? [duplicate]
(5 answers)
Closed 3 months ago.
i am trying to connvert
double[] v = { 5, 4, -8, 2, 6 };
to a String with a method.
I created an method called ToString(double[] v);
and tried to do it with an foreach loop, but every time i insert a double the console gives out system.double instead of the string.
for university i am only allowed to use convert.toString and no parse and i should use it as a method
Thanks for your support.
Benjamin
The correct way to do this would be to use string.Join
var myString = string.Join(", ", myDoubles);
But if you want to do the same thing yourself it is fairly easy to do:
var sb = new StringBuilder();
foreach(var myDouble in myDoubles){
sb.Append(Convert.ToString(myDouble)).Append(",");
}
var myString = sb.ToString();
If you are not allowed to use stringBuilder either you can just concatenate strings instead, just keep in mind that increases the algorithmic complexity, and is not really something you should do, or even teach as an example.
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed last year.
Here's my code:
using System;
public class Program
{
private static string[] ar = new string[] {};
public static void Main()
{
ar[0] = "hello";
Console.WriteLine("Total array length: " + ar.Length);
}
}
It show the error below when I run the above code:
Run-time exception (line 10): Index was outside the bounds of the array.
I thought that's how to define a dynamic array in C# but I must be missed something here.
You create an empty array, that is an array with fixed length 0 and no entries.
Consider List<string> ar = new List<string>() instead.
Related thread: Dynamic array in C#
EDIT: It later turned out the asker could use a Dictionary<int, string>. For a Dictionary<,>, the set accessor of the indexer (by which I mean the syntax ar[0] = "hello") will either create a new key/value pair (0 → "hello"), or overwrite the value of an already existing key (0).
Declaring private static string[] ar = new string[] {} actually means that you have an array of string with size of 0, i.e., empty array. C# doesn't allow to resize an array so you should initialize the array size if the length is fixed and this the reason you are getting the error Index was outside the bounds of the array. you are trying to set a value to an index which is larger then the array length.
In case the length is not fixed and you want to be dynamic, I recommend using List. Lists use arrays to store the data so you get the speed benefit of arrays with the convenience of a LinkedList by being able to add and remove items without worrying about having to manually change its size.
List<string> myList = new List<string>();
myList.Add("hello");
myList.Add("Ola");
private static string[] ar = new string[] {};
The above will create an empty array of string (i.e. allowed length = 0) and hence the IndexOutOfBound exception.
When you are not certain of the size of your collection, use List.
For e.g.: -
List<string> ar= new List<string>();
ar.Add("hello");
ar.Add("Ola");
I initiated an empty array - line.
string[] line = new string[] { };
I want to store every line that would be outputed in a cmd processing with the while loop below. This seems to work easily if I store the values in a string variable.
As shown below:
while (!proc.StandardOutput.EndOfStream)
{
line = proc.StandardOutput.ReadLine();
}
However, I'm not sure how to store the values as separate elements in the array. I've tried:
while (!proc.StandardOutput.EndOfStream)
{
for(a in line)
{
a = proc.StandardOutput.ReadLine();
}
}
But its not working.
This is probably a very basic question. But I'm still learning C#.
There are few solutions. One would be to use List<string> instead of string[]:
List<string> line = new List<string>();
And than add lines next way:
while (!proc.StandardOutput.EndOfStream)
{
line.Add(proc.StandardOutput.ReadLine());
}
An array works on the basis of indexing. So if you want to use an array you need to specify how long it has to be or in other words how many items it can contain:
// this array can store 100 items
string[] line = new string[100];
To access a certain position you need to use the [ ] operator and to move forward in the array you need an indexing variable of type int that you can increment each iteration
int indexer = 0;
while (!proc.StandardOutput.EndOfStream)
{
line[indexer] = proc.StandardOutput.ReadLine();
indexer ++; // increment
}
This way you need to know in advance how many items you want to deposit in your array.
Another way would be to use a flexible collection like List which can dynamically grow. Sidenote: The indexing works with the same [ ] operator, but the adding of items works via the Add method
If you want to know more have look at this overview of possible collection types
This question already has answers here:
C# multidimensional arrays iteration
(5 answers)
Closed 2 years ago.
I am trying to print out my array of numbers that I have assigned to a particular array. My algorithm for choosing numbers consists of choosing a random number that is not a duplicate and storing it inside the array.
Pretty simple really, but I have no idea as to why it is printing out this error.
int[] ticket1 = new int[4];
for (int i = 0; i < 4; i++)
{
int temp = rand.Next(43);
while (ticket1.Contains(temp))
{
temp = rand.Next(43);
}
ticket1[i] = temp;
}
Console.WriteLine("{0}{1}", item.PadRight(20), ticket1.ToString());//ticket1 produces System.Int32[] instead of 4 numbers.
//I have changed this line to:
//Console.WriteLine("{0}{1}", item.PadRight(20), string.Join(",", ticket1));
//And it still doesn't work. the error remains. (System.Int32[])
My question is, how can I print out my 4 numbers (beside each other) in string format.
//EDIT: I've found my problem. I am putting my ticket1 inside a foreach loop, it's somehow not reaching out to the array values and it therefore prints out System.Int32[] instead.
All fixed.
If you call ToString() on an array like that, you simply get the full name of the type of class.
You could fix it a few ways. Print only the current item inside the loop, or print each item one at a time outside of the loop:
Console.WriteLine("{0}{1}", item.PadRight(20), ticket1[0]);
Console.WriteLine("{0}{1}", item.PadRight(20), ticket1[1]);
// etc...
Or "flatten" the collection before printing:
Console.WriteLine("My numbers: ", String.Join(", ", ticket1));
ticket1.ToString() does not print the content of the array, only its type, because this is the way the ToString() method is implemented on arrays.
You can fix this in several ways - for example, by using string.Join method:
Console.WriteLine("{0}{1}", item.PadRight(20), string.Join(",", ticket1));
Because you are not writing your array elements, you are writing your array itself, that's why ToString() generates it's full type name.
Change your ticket1.ToString() to ticket1[i] in your for loop.
for (int i = 0; i < 4; i++)
{
int temp = rand.Next(43);
while (ticket1.Contains(temp))
{
temp = rand.Next(43);
}
ticket1[i] = temp;
Console.WriteLine("{0} {1}", item.PadRight(20), ticket1[i]);
}
If you don't want to print it inside your for loop, then you can use String.Join to concatenate all your elements in your array in a simple string like;
for (int i = 0; i < 4; i++)
{
int temp = rand.Next(43);
while (ticket1.Contains(temp))
{
temp = rand.Next(43);
}
ticket1[i] = temp;
}
Console.WriteLine("{0} {1}", item.PadRight(20), string.Join(",", ticket1));
Because when you call .ToString() on an object you get the type of that object. For basic primitive (value) types this behavior is overridden to output the value. But for something like an array there's no "default" string representation, so the behavior you're seeing is the default.
You could wrap your data in an object and override .ToString() on that object. If you have to output the values in many places in the code that would be the way to go so you only have to write the logic once. ("Smart data structures and dumb code works a lot better than the other way around." - Eric Raymond)
But if you only need to do it here then you can just output the values directly. Basically join the values as a string in whatever representation you want. For example, if they should be comma-separated:
Console.WriteLine(
"{0}{1}",
item.PadRight(20),
string.Join(",", ticket1));
Say I have
List<int> ages = new List<int>() { 8, 5, 3, 9, 2, 1, 7 };
List<int> marks = new List<int>() { 12, 17, 08, 15, 19, 02, 11 };
I can sort my marks by ages like this:
while (true)
{
bool swapped = false;
for (int i = 0; i < ages.Count - 1; i++)
if (ages[i] > ages[i + 1])
{
int tmp = ages[i];
ages[i] = ages[i + 1];
ages[i + 1] = tmp;
tmp = marks[i];
marks[i] = marks[i + 1];
marks[i + 1] = tmp;
swapped = true;
}
if (!swapped)
break;
}
Now I want to put this into a function that accepts any two lists. The first parameter will be the reference list, the numerical or comparable list. The second parameter will be the list containing the data.
For example:
public static void Sort<T>(List<T> RefList, List<T> DataList)
{
// sorting logic here...
}
There are a few problems:
First of all, T is almost certainly not the same type in RefList and DataList. RefList might be dates, integers, or doubles; whereas DataList is free to be absolutely anything. I need to be able to receive two, arbitrary generic types.
Secondly, I cannot seem to use the > operator with the T in this line:
if (ages[i] > ages[i + 1])
Perhaps my whole approach is wrong.
By the way, I have read responses to similar questions that suggest that the two lists should be combined into a single list of a compound data type. This isn't practical at all for my application. All I want to do is write a static function that somehow sorts one list based on the elements of another.
To sort one list the way you want you actually need to somehow keep references from items in first list to they weight/keys in the second list. No existing methods do that as you can't easily associate metadata with arbitrary values (i.e. if first list is list of int as in your case there is nothing to map to keys in second list). Your only reasonable option is to sort 2 lists at the same time and make association by index - again no existing classes to help.
It may be much easier to use solution that you reject. I.e. simply Zip and OrderBy, than recreate first list:
ages = ages
.Zip(marks, (a,m)=> new {age = a; mark = m;})
.OrderBy(v => v.mark)
.Select(v=>v.age)
.ToList();
Note (courtesy of phoog): if you need to do this type of sorting with Array there is Array.Sort that allows exactly this operatiion (see phoog's answer for details).
There's no framework method to do this with List<T>, but if you don't mind putting the data into two arrays, you can use one of the Array.Sort() overloads that takes two arrays as arguments. The first array is the keys, and the second is the values, so your code might look like this (leaving aside the step of getting arrays from the lists):
Array.Sort(ages, marks);
The specifics of getting the values into arrays and then back into lists would depend, among other things, on whether you need to end up with the same list sorted appropriately or whether it's okay to return a new list with the data in the desired order.
Use:
public static void Sort<TR, TD>(IList<TR> refList, IList<TD> dataList)
where TR : System.IComparable<TR>
where TD : System.IComparable<TD>
{
...
}
and then use:
refList[i].CompareTo(refList[i+1])
instead of the operators.
.Net numbers already implement IComparable, and you can use overloads that allow you to specify a different IComparable.
If I understand "I can sort my marks by ages like this:" properly,
I would like to suggest the below to eliminate much confusion.
struct Student{
int age;
int marks;
};
List<Student> students = {{8,12}, ...};
Now you can sort according to age and marks is accordingly sorted automatically.
If it is not possible, you need to fix the code as below.
First of all, T is almost certainly not the same type in RefList and DataList.
Then you need 2 parameters T1, T2. Just T implies the types are the same.
public static void Sort<RefType, DataType>(List<RefType> RefList, List<DataType> DataList)
{
You can also zip the two lists together as suggested by Mechanical Snail and explained in Looping through 2 Lists at once