I'm having some trouble letting a user save his value into an array, here's the code that I tried with:
I want to be able to store up to 4 objects, and then reset them with null, if that is possible.
string [] array = new string[4];
array[i] += Console.ReadLine(); //and now it says: Cannot implicitly convert
type 'string' to 'int'. I also want to reset the value with this code:
array[i] = null;
I'm new to arrays and it's really hard. Thanks in advance!
The problem is in i variable that has a type string instead of int. You need to use integer values for your indexer in array.
Also there is no reason to use += operator. Just assign your value to the array element by using =.
var index = int.Parse(i); // the better way is to use TryParse to check your i string contains integer value
array[index] = Console.ReadLine();
Looks to me like you are trying to index the array using a name. If so, I would use a Dictionary instead:
var key = "MyValueKey"; //I presume this is currently your "i" value
var dict = new Dictionary<String, String>();
var userVal = Console.ReadLine();
if (String.IsNullOrWhitespace(userVal))
userVal = null;
if (dict.ContainsKey(key))
dict[key] = userVal;
else
dict.Add(key, userVal);
Related
We may access the last index of a list/array by the following:
var l = new List<string> {"1", "2a", "3cd"};
Console.WriteLine(l[^1]);
output: "3cd"
May I know if it is possible to cast the string ^1 to index object:
(second line is not working)
var s = "^1"
var index = (Index) s;
Console.WriteLine(l[index]);
To get the output: "3cd"
To instantiate an Index for one from the end, do this.
var index = new Index(1, true);
or
var index = Index.FromEnd(1);
var s = "^1"
just makes a string that uses the '^' char, that can be used in code, to indicate an Index from end.
There is no conversion, explicit or implicit between string and Index.
If, for some reason you wanted to read a Index struct from JSON, you could store both,
int value
and the optional
bool fromEnd = false
and use those to instantiate a new instance. This would be simpler than writing a parser for strings that contain index expressions.
I know a string is immutable and cannot be redefined, but in this foreach loop the string is changed multiple times by adding elements of an array.
var stringOfNames = "";
var arrayOfNames = new string[5] { "jack", "marry", "joe", "jimmy", "bud" };
foreach (var item in arrayOfNames)
{
stringOfNames += item;
Console.WriteLine(stringOfNames);
}
Expected:
An error stating "Variable is already defined in this scope."
Actual:
The string is changed by adding the other names.
Also, what's the difference between these two:
1)
var a = "something";
var a = "something else";
2)
var a = "something";
a+= "asdf";
Why does the second option work?
but in this foreach loop the string is changed
No, it's not.
The variable changes value, to refer to a different string on each iteration. Each of the string objects in question - both the original ones in the array and the intermediate results - stays with the same data that it had before.
Here's another way to demonstrate that:
string x = "ab";
string y = x;
x += "cd";
Console.WriteLine(x); // abcd
Console.WriteLine(y); // ab
Here the value of x changes to refer to a new string, but the value of y still refers to the original string, "ab".
Basically you need to be very clear about three separate concepts:
Variables: named storage locations which store values
References: one kind of value, which refers to an object.
The objects themselves
I have an answer on another question which may help clarify the differences.
stringOfNames += item; does not define the variable stringOfNames, it assigns a value to it.
How can I convert an array of string to enum?
The following code gives a basic idea about what is expected,
permission.Permissions.Add(Enum.Parse(typeof(PagePermission) ,a );
however, it throws an error like
can not convert object to enum.
Here, PagePermission is enum.
string pagePermission = "View,Edit";
string[] permissions = pagePermission.Split(',');
permission.Permissions = new List<PagePermission>();
for (int i = 0; i < permissions.Length; i++)
{
string a = permissions[i];
permission.Permissions.Add(Enum.Parse(typeof(PagePermission) ,a );
}
Use this
IEnumerable<myEnum> items = myArray.Select(a => (myEnum)Enum.Parse(typeof(myEnum), a));
Enum.Parse returns an object, you need to cast it to the actual enum type. In your case:
permission.Permissions.Add((PagePermission)Enum.Parse(typeof(PagePermission), a);
Otherwise you'd be adding an object to a list of PagePermission, which causes the error you had.
I want to know whether we can give the index of the string as Long data type.
var i=long.Parse(Console.ReadLine());
var result = testString[i-1];
the second line giving me the error by saying that "The best overloaded method match for 'string.this[int]' has some invalid arguments."
No you can't use long for most collection types (you haven't specified what testString is).
One way to get around this would be to segregate the string into a multi-part / multi-dimension array then use a multiplier to get which part of the array to check.
For example:
Your index is 100,000 and you have an array of shorts (32,767 length)...
string[,] testString = new string[100, 32766]; //Replace this with your Initialisation / existing string
var arrayRank = (int)Math.Round((double) 100000 / 32767, 0);
var arrayIndex = (int)Math.Round((double)100000 % 32767, 0);
//Test this works.
//testString[arrayRank, arrayIndex] = "test"; - Test to see that the array range is assignable.
var result = testString[arrayRank, arrayIndex]; //Test value is what we expect
This may not be the most efficient way to go about things, but it is a workaround.
No, it cannot accept a long. The only overload accepts an int indexer. You would need to change your code to int.Parse() instead of long.Parse()
There is no way to pass long as an index of array, compiler doesn't allow that.
Workaround can be converting the long to int, this is called narrow conversion.
var result= testString[(int)i)];
I have declared my int[] as follows
int[] iroleID = new int[] { };
My code for getting the values from database and assigning to iroleid is as follows
if (oAuthenticate.getTaskID(out m_oDataSet1, "uspgetTaskID"))
{
for (int iTaskid = 0; iTaskid < m_oDataSet1.Tables[0].Rows.Count; iTaskid++)
{
iroleID = Convert.ToInt32(m_oDataSet1.Tables[0].Rows[iTaskid]["RoleID"].ToString());
strTaskID = m_oDataSet1.Tables[0].Rows[iTaskid]["TaskID"].ToString();
arrTaskID.Add(strTaskID);
}
}
But i am getting an error as mentioned Cannot implicitly convert type 'int' to 'int[]' can any one help me
And no surprise here. Look at
iroleID = Convert.ToInt32(...);
Convert.ToIn32 results in an int just like the compiler claims.
Either do something like:
if (oAuthenticate.getTaskID(out m_oDataSet1, "uspgetTaskID"))
{
var iroleID = new int[m_oDataSet1.Tables[0].Rows.Count];
for (int iTaskid = 0; iTaskid < m_oDataSet1.Tables[0].Rows.Count; iTaskid++)
{
iroleID[iTaskid] = Convert.ToInt32(m_oDataSet1.Tables[0].Rows[iTaskid]["RoleID"].ToString());
/* ... */
}
}
or rethink your algorithm.
PS: I can hardly tell you what exactly to do as you don't show what the purpose of iRoleID is.
off course!
iroleID = Convert.ToInt32(m_oDataSet1.Tables[0].Rows[iTaskid]["RoleID"].ToString());
iroleID is an int array; Convert.ToInt32() returns an int .
so:
-you must declare an int variable tu store Convert.ToInt32() value
or
-just add Convert.ToInt32() result to iroleID ( iroleID.Add(Convert.ToInt32(...)) )
Sure, you can't just assign the int value to the int[] variable. Probably you need to add items to the collection. Change your int[] iroleID = new int[] { }; to List<int> iroleID = new List<int>(); and then change code to:
if (oAuthenticate.getTaskID(out m_oDataSet1, "uspgetTaskID"))
{
for (int iTaskid = 0; iTaskid < m_oDataSet1.Tables[0].Rows.Count; iTaskid++)
{
iroleID.Add(Convert.ToInt32(m_oDataSet1.Tables[0].Rows[iTaskid]["RoleID"].ToString()));
strTaskID = m_oDataSet1.Tables[0].Rows[iTaskid]["TaskID"].ToString();
arrTaskID.Add(strTaskID);
}
}
iroleID = Convert.ToInt32(m_oDataSet1.Tables[0].Rows[iTaskid]["RoleID"].ToString());
This would convert the RoleID columns value to an integer. You are taking this integer and trying to assign it to an integer array which of course is not possible. What exactly is your idea? If it is to populate a single array with all the IDs you can do the same as you did but assign it to a normal integer and then add that integer to a list or something.
You can also just use plain ADO.NET to retrieve all the values from that column and cast it to an List. That would be better.
One problem has already been answered, you must add it to an array giving the position you want
iroleID[iTaskid] = Convert.ToInt32(m_oDataSet1.Tables[0].Rows[iTaskid]["RoleID"].ToString());
the other problem is, that you create an array. You must give the length of the array.
int[] iroleID = new int[m_oDataSet1.Tables[0].Rows.Count];
Use indexing for the int array to assign a value, you can't assign an integer directly to an integer array.
iroleID[0] = Convert.ToInt32(m_oDataSet1.Tables[0].Rows[iTaskid]["RoleID"].ToString());