I am trying to get an item from a char array based on the index that I have. I have used code earlier to get the index of a specified item but now I want the opposite, to get the item of the specified index. I have tried a few things but can't get it working.
I would like something like this:
char arrayChar = Array.GetItem(index [i]) // I know this isn't right but just so you get the idea.
Thanks very much!
Assuming your char array is called ArrayOfChars and the index is i. It should be as simple as
char arrayChar = ArrayOfChars[i];
var arrayChar = yourArray[index];
Related
I am trying to read the last line of a text file into an array so that I am able to get a specific element of the array by index, but I am having trouble doing this as 1 line in my text file has many elements that need to go into the array as opposed to there being 1 element per line, so for reference my text file line structure would be like so: element1,element2,element3... It is similar in structure to that of a csv file.
My code so far that is not working:
string lastline = System.IO.File.ReadLines(myfilepath).Last();
string[] id = new string[](lastline.Split(','));
Then after inserting the line to my array I would like to pull an element of the array by the index, for example I want to pull element2 from the array and assign it to var item2, but am not sure how to go about that.
Not sure if I understood your question completely, but getting single string from a string array by index:
string lastline = System.IO.File.ReadLines(myfilepath).Last();
string[] id = lastline.Split(',');
//string result = id[index];
/* Better way */
string result = id.ElementAtOrDefault(index);
Where index is the zero-based index of the items. So, the first string's index would be 0, next 1 etc. Thanks to Steve for pointing out the error in creating the array and the hint to avoid IndexOutOfRangeException.
The method ElementAtOrDefault(index) will return the element at index, or if the index is out of range, return a default element, which in this case is an empty string.
I have a multi-dimensional array in a text file:
a,1,2,3
b,4,5,6
c,7,8,9
d,10,11,12
I want to input one of the numbers, search the array, and display the corresponding letter for the row the number appears in.
Any help would be greatly appreciated.
Edit:
I have a csv file containing the information given above.
So far I have:
1. Created an array to store the read all the lines in the file
2. Created a second array to store the final array values
3. Created a third array to store the line splits at , and place values back into second array.
This is the code:
string[] as_FirstArray = System.IO.File.ReadAllLines("PartNumbersFile.csv");
string[,] as_SecondArray = new string[4, as_FirstArray.Length];
string[] as_ThirdArray;
string s_Input = Console.ReadLine();
for (int i_Count1 = 0; i_Count1 < as_FirstArray.Length; i_Count1++)
{
as_ThirdArray = as_FirstArray[i_Count1].Split(',');
as_SecondArray[0, i_Count1] = as_ThirdArray[0];
as_SecondArray[1, i_Count1] = as_ThirdArray[1];
as_SecondArray[2, i_Count1] = as_ThirdArray[2];
as_SecondArray[3, i_Count1] = as_ThirdArray[3];
}
And now I'm totally stuck. I have been told that, from here, I need to:
1. use a for loop on as_SecondArray index[1] from first row to last row.
2. use an if statement to determine if userinput is found in index[1] and, if so, store the loop count number. (Here, if no match is found, I will repeat for index[2] and again, if no match found, repeat for index[3].)
3. use another for loop and if statement on index[0] to match the count number from the found match, and display the corresponding entry. (I can do this step but that's hopeless without knowing how to do steps 1 and 2.)
I don't how to specify a particular index as the loop target. Or where I place the loop in relation to the loop I already have - inside it or not.
Edit:
THANK YOU TO WHOEVER EDITED MY POST AND I HAVE NOW DELETED MY ANSWER :-)
After A LOT more time I have made a little progress. I have figured out how to loop a particular index and identify if userinput is found in that index:
for (int i_Count2 = 0; i_Count2 < as_SecondArray.GetLength(1); i_Count2++)
{
for (int i_Count3 = 0; i_Count3 < as_SecondArray.GetLength(0); i_Count3++)
{
if (as_SecondArray[1, i_Count3].Equals(s_Input))
{
s_Found = as_SecondArray[1, i_Count3];
}
else { lblOutput.Text = "not found"; }
}
}
But I am stuck at how to retrieve the i_Count3 loop number.
Don't create multidimensional array instead create a Dictionary or Hashtable where key will be the number and value will be the letter. Now you can easily search the number and find associated letter with the search time of O(1).
I've got a string[] Brands = new string[10];
With the following code i'm giving it 4 standard values. I can add values with a add button. (I already got this part of code)
public Form1()
{
{
InitializeComponent();
Merken[0] = "Yamaha";
Merken[1] = "Suzuki";
Merken[2] = "Harley";
Merken[3] = "Kawasaki";
merkNr = 4;
listBoxMotoren.DataSource = Brands;
}
}
I want to display the FILLED elements of the array into a `label.text.
So, when I run the program the label shows the numer 4 (because 4 elements of the array are filled). When I add a value to the array with btnclick, the label needs to display the number 5 and so on...`
You can use Linq to get count of filled elements from array.
int count = Merken.ToList().Where(x => (!string.IsNullOrEmpty(x))).Count();
yourLabel.Text = count.ToString();
An easier way would be to use a List<string> and display the Count() of the list. Lists are data structures which grow dynamically, thus each time you add an item to the list, the list grows automatically.
If you want to use arrays, you could start from the first element and use the String.IsNullorEmpty(string str) and a counter which is incremented each time you find a string which is neither null or empty.
Once that you hit a null/empty string, you stop your loop and display the counter.
Forgive me if I'm interpreting this as more simple than it is, but as far as I can tell all you need to do is add "[name of label on form].Text = Merken.Count().ToString();" in the code that adds the new item.
Is there a particular reason you used Merken in the setup but declared it initially as Brands?
why you arent using List
it has Count property. and if you need array for export you call .ToArray() method to get array of your list.
Will you ever have blank indexes?
Merken[4] = ""
Merken[5] = "Honda"
If you are not going to ever have blank indexes, you can set your label to:
[arrayName].length
This will add together the number of indexes in the array.
EDIT: OP says there will be blank indexes
I would recommend looping through the array to see which indexes have values and then increment a counter which you will set as the label text.
int indexesWithValues = 0;
for (int i = 0; i < Brands.length; i++)
{
if (Brands[i] != "")
{
indexesWithValues++;
}
}
Then you set your label text to the counter.
You can get the number of elements in array using
Using System.LINQ
-----
Marken.Count();
If I have a table , with row with numbers like 70-0002098, lets just call the row, ID
I need the last 4 numbers for all the table rows,
So what I need is something like
foreach(var row in table)
{
var Id = row.ID(but just the last 4 digits)
}
Not sure what format you want to store it as, or what you want to do with it after, but...
Edit: Added an if check for length to avoid index out of bounds condition. Also corrected syntax- SubString() => Substring()
int count = 0;
foreach(var row in table){
string temp = row.ID.ToString();
count += (temp.Length > 5)? Convert.ToInt32(temp.Substring(temp.Length-5, 4)) : Convert.ToInt32(temp);
}
// But I have no idea what datatype you have for that or what
// you want to do (count up the integer values or store in an array or something.
// From here you can do whatever you want.
Your illustration suggests that the RowID is not currently a number (its got a hyphen in it) so I assume its a string
id.Right(4);
will return the right four characters. It doesn't guarantee they are numbers though. Right is an extension method of string which can be easily written, or copied from this thread Right Function in C#?
This is probably a really easy question, I want to access the last element of:
List<string>[] list = new List<string>[3];
So each list inside has 3 elements but how should I access the last of those lists?
You can use Enumerable.Last():
string lastElement = list.Last().Last();
The first call will return the last List<string>, and the second will return the last string within that list.
Alternatively, since you know the length of the array, you can access the list directly, and do:
string lastElement = list[2].Last();
If you know, in advance, that you're always going to have 3 lists with 3 elements, you might want to consider using a multidimensional array instead:
string[,] matrix = new string[3,3];
// fill it in..
string last = matrix[2,2];
If you have [[1,2,3],[4,5,6],[7,8,9]] and you want 9, use list.Last().Last(). If you want [3,6,9], use list.Select(sublist => sublist.Last()).
In C# 8.0 you can use the "hat" operator (^) to select an element from the end of a list.
The index from end operator ^, which specifies that an index is
relative to the end of the sequence.
// get last item from last array
string last = list[^1][^1];