System.IndexOutOfRangeException for a dynamic initialized array - c#

var objTypeIndex = from u in context.sistema_DocType_Index where u.docTypeId == id select u.indexId;
indexIds = objTypeIndex.ToList();
int count = indexIds.Count();
string[] names = new string[] {};
int i = 0;
foreach (int indexId in indexIds)
{
//resgata nome do indice e armazena em um array
string strIndiceID = indexId.ToString();
int indiceID = Convert.ToInt32(strIndiceID);
var objIndexName = from u in context.sistema_Indexes where u.id == indiceID select u.idName;
name =
names[i] = objIndexName.First();
i++;
}
This line above the last:
names[i] = objIndexName.First();
gives the following error:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
I know what that means.. I just can´t figure out why.

Look here:
string[] names = new string[] {};
You've created an empty array. You can't put any element into that array. There is no value of i for which this statement will work:
names[i] = objIndexName.First();
It's not clear what you're trying to do, but perhaps you want a List<string> to build up (with Add) rather than an array? Or you could probably do the whole thing with a single LINQ query...

Replace
string[] names = new string[] {};
By
var names = new List<string>();
And instead of
names[i] = objIndexName.First();
Use
names.Add(objIndexName.First());
Then, you will be able to get your array as follow:
var nameArray = names.ToArray();

Related

How can I split a string to store contents in two different arrays in c#?

The string I want to split is an array of strings.
the array contains strings like:
G1,Active
G2,Inactive
G3,Inactive
.
.
G24,Active
Now I want to store the G's in an array, and Active or Inactive in a different array. So far I have tried this which has successfully store all the G's part but I have lost the other part. I used Split fucntion but did not work so I have tried this.
int i = 0;
for(i = 0; i <= grids.Length; i++)
{
string temp = grids[i];
temp = temp.Replace(",", " ");
if (temp.Contains(' '))
{
int index = temp.IndexOf(' ');
grids[i] = temp.Substring(0, index);
}
//System.Console.WriteLine(temp);
}
Please help me how to achieve this goal. I am new to C#.
If I understand the problem correctly - we have an array of strings Eg:
arrayOfStrings[24] =
{
"G1,Active",
"G2,Inactive",
"G3,Active",
...
"G24,Active"
}
Now we want to split each item and store the g part in one array and the status into another.
Working with arrays the solution is to - traverse the arrayOfStrings.
Per each item in the arrayOfStrings we split it by ',' separator.
The Split operation will return another array of two elements the g part and the status - which will be stored respectively into distinct arrays (gArray and statusArray) for later retrieval. Those arrays will have a 1-to-1 relation.
Here is my implementation:
static string[] LoadArray()
{
return new string[]
{
"G1,Active",
"G2,Inactive",
"G3,Active",
"G4,Active",
"G5,Active",
"G6,Inactive",
"G7,Active",
"G8,Active",
"G9,Active",
"G10,Active",
"G11,Inactive",
"G12,Active",
"G13,Active",
"G14,Inactive",
"G15,Active",
"G16,Inactive",
"G17,Active",
"G18,Active",
"G19,Inactive",
"G20,Active",
"G21,Inactive",
"G22,Active",
"G23,Inactive",
"G24,Active"
};
}
static void Main(string[] args)
{
string[] myarrayOfStrings = LoadArray();
string[] gArray = new string[24];
string[] statusArray = new string[24];
int index = 0;
foreach (var item in myarrayOfStrings)
{
var arraySplit = item.Split(',');
gArray[index] = arraySplit[0];
statusArray[index] = arraySplit[1];
index++;
}
for (int i = 0; i < gArray.Length; i++)
{
Console.WriteLine("{0} has status : {1}", gArray[i] , statusArray[i]);
}
Console.ReadLine();
}
seems like you have a list of Gxx,Active my recomendation is first of all you split the string based on the space, which will give you the array previoulsy mentioned doing the next:
string text = "G1,Active G2,Inactive G3,Inactive G24,Active";
string[] splitedGItems = text.Split(" ");
So, now you have an array, and I strongly recommend you to use an object/Tuple/Dictionary depends of what suits you more in the entire scenario. for now i will use Dictionary as it seems to be key-value
Dictionary<string, string> GxListActiveInactive = new Dictionary<string, string>();
foreach(var singleGItems in splitedGItems)
{
string[] definition = singleGItems.Split(",");
GxListActiveInactive.Add(definition[0], definition[1]);
}
What im achiving in this code is create a collection which is key-value, now you have to search the G24 manually doing the next
string G24Value = GxListActiveInactive.FirstOrDefault(a => a.Key == "G24").Value;
just do it :
var splitedArray = YourStringArray.ToDictionary(x=>x.Split(',')[0],x=>x.Split(',')[1]);
var gArray = splitedArray.Keys;
var activeInactiveArray = splitedArray.Values;
I hope it will be useful
You can divide the string using Split; the first part should be the G's, while the second part will be "Active" or "Inactive".
int i;
string[] temp, activity = new string[grids.Length];
for(i = 0; i <= grids.Length; i++)
{
temp = grids[i].Split(',');
grids[i] = temp[0];
activity[i] = temp[1];
}

How to make string list to "string array"

This is what I want to convernt: {"apple", "banana"} to "["apple", "banana"]"
I have tried convert string list to string array first, then convert string array to string, but did not work.
var testing = new List<string> {"apple", "banana"};
var arrayTesting = testing.ToArray();
var result = arrayTesting.ToString();
You can use string.Join(String, String[]) method like below to get a , separated string values (like csv format)
var stringifiedResult = string.Join(",", result);
You can try this, should work;
var testing = new List<string> { "apple", "banana" };
var arrayTesting = testing.ToArray<string>();
var result = string.Join(",", arrayTesting);
You can also use StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append("\"[");
for (int i = 0; i < arrayTesting.Length; i++)
{
string item = arrayTesting[i];
sb.Append("\"");
sb.Append(item);
if (i == arrayTesting.Length - 1)
{
sb.Append("\"]");
}
else
sb.Append("\",");
}
Console.WriteLine(sb);
Instead of converting it to an array, you could use a linq operator on the list to write all the values into a string.
string temp = "";
testing.ForEach(x => temp += x + ", ");
This will leave you with a single string with each value in the list separated by a comma.

How to make from List<ClassName> two strings array (Names, Values)?

I've the following class:
class Node
{
public string NameField{ get; set; }
public string ValueField{ get; set; }
}
And also have a list of Nodes as var test = new List<Node>, I need to make two strings arrays as string[], first contains all the NameField and the second contains all the ValueField, I did the following code:
string[] NameField = new string[test.Count];
string[] ValueField = new string[test.Count];
int i = 0;
foreach (var s in prefsNameValueArray)
{
NameField[i] = s.CTMAttrName;
ValueField[i] = s.CTMAttrValue;
i++;
}
Can I do the same using LINQ, can anybody help me to improve this code?
Thanks in advance,
Ramzy
With Linq:
string[] NameFields = nodes.Select(n => n.NameField).ToArray();
string[] ValueFields = nodes.Select(n => n.ValueField).ToArray();
Linq is not necessarily the most efficient way here since ToArray could create an array which may be too large(due to the doubling algorithm) if you use a query instead of a collection. But it is short and readable (and fast enough mostly).
This is the for-loop version:
int count = nodes.Count(); // in case you want to change the collection type or use a linq query
string[] NameField = new string[count];
string[] ValueField = new string[count];
for (int i = 0; i < count; i++)
{
NameField[i] = nodes.ElementAt(i).NameField;
ValueField[i] = nodes.ElementAt(i).ValueField;
}
var nameField = test.Select(n => n.CTMAttrName).ToArray();
var valueField = test.Select(n => n.CTMAttrValue).ToArray();
Using Lambda expressions;
string[] NameField = prefsNameValueArray.Select(x=> x.NameField).ToArray();
string[] ValueField = prefsNameValueArray.Select(x=> x.ValueField).ToArray();

how to assign empty to string array in c#

How can I assign empty to string array in c#?
string [] stack; //string array
how to assign
stack = ""; //this statement gives error cannot implicitly convert to type string to string []
You cannot use:
string[] stack = "";
Since stack in here is an array of string. If you want to initialize empty string for each elements in array, you can use LINQ with Enumerable.Range to get the result, assume there are 10 items in here:
string[] stack = Enumerable.Range(0, 10)
.Select(i => string.Empty)
.ToArray();
This will create an array with three empty strings.
string[] arr1 = new string[] { "", "", "" };
or if you only need one:
string[] arr1 = new string[] { "" };
or another example (with 3 strings):
string[] arr1 = new string[3];
arr1[0] = "";
arr1[1] = "";
arr1[2] = "";
Just iterate over the array like this:
int length = stack.Length;
for(int i = 0; i < length; i++)
{
stack[i] = string.Empty;
}
If you just want to create empty array of string[] object.
string [] stack = new string[]{};

Saving selected listbox(binded) items to an array in c#

string[] chkItems = new string[4];
string[] str = new string[4];
str[0] = txtID.Text;
str[1] = txtName.Text;
str[2] = txtEmail.Text;
itemCount = ltbxInterests.SelectedItems.Count;
for (int i = 0; i <= itemCount; i++)
{
ltbxInterests.SelectedItems.CopyTo(chkItems, 0);
// here it is returning an exception
//"Object cannot be stored in an array of this type."
}
Please help me how to get out from this exception
Couple issues here, chkItems is defined as length 4 so you will get an exception if you try and put more than 4 items in. The source array SelectedItems is of type object so you would need to cast the result.
Assuming you are only putting strings into the listbox you could use (remember to reference System.Linq)
string[] str = new string[4];
str[0] = txtID.Text;
str[1] = txtName.Text;
str[2] = txtEmail.Text;
string[] chkItems = ltbxInterests.SelectedItems.OfType<string>().ToArray();
If you are wanting to limit to the first 4 items, you could replace the last line to
string[] chkItems = ltbxInterests.SelectedItems.OfType<string>().Take(4).ToArray();
Also you could shorten the code to use an array initializer (but this wil make str length 3 because you only have 3 items):
string[] str = new [] {
txtID.Text,
txtName.Text,
txtEmail.Text,
}
SelectedItems is a collection of Object, then, in order to use CopyTo methods, chkItems must be an array of type object (i.e. object[]).
Otherwise, you can use LINQ to convert, for example, to a list of strings:
var selectedList = ltbxInterests.SelectedItems.OfType<object>()
.Select(x => x.ToString()).ToList();
You chould check the Type of > chkItems .

Categories