C# Last Element of List of List - 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];

Related

How to read a line of a text file into an array using c# and then get element by index

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.

Add an item to an already existing 2D integer array in a function in windows form C#

I have a 2D integer array and i want to add an item in it as per the values i get in the method.
private int[,] indexes = new int[100,2];
This is the array declared and below is how i add items in the array as per the indexes but in my method i would not know the exact indexes. Is there a way where in i can get the indexes of the last element in the array and than add an element to it or a way where i can add directly at the end of the existing array
indexes[0,0]= currRowIndex;
indexes[0,1] = 0;
Here i have added at the index 0. Similarly i should be able to add to the last index where the elements in an array ends.
Consider of using nested lists - List<List<int>> From MSDN List
Then new values will be added always to the end of collection
List<List<int>> indexes = new List<List<int>>();
indexes.Add(new List<int> { 1, 2 });
And retrieve value by index
int firstValue = indexes[0][0];
int secondValue = indexes[0][1];
indexes .GetLength(0) -> Gets first dimension size
indexes .GetLength(1) -> Gets second dimension size
so you can add items to the list as
indexes[indexes .GetLength(0),
indexes .GetLength(1)] = value;

Count the filled array elements and display result into label

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();

How to find an item in an array that sum of all values before that is a spcific value? (C++ and C#)

Assume that I have an array of integers with a specific size (say 1000)
I want to find the index of an item in this array, given the sum of all items in the array before this item (or including this item).
for example assume that I have the following array:
int[] values={1,2,3,1,3,6,4,8,2,11}
Input value is 6, then I need to return the index 2 (zero based indexing for 3 in above example) and when given 10, I should return the index 4.
What is the fastest way to do this? in C++ and c#?
If you need to do it only once, then the naive way is also the fastest way: walk the array, and keep the running total. Once you reach the target sum, return the current index.
If you need to run multiple queries for different sums, create an array and set up sums in it, like this:
var sums = new int[values.Length];
sums[0] = values[0];
for (int i = 1 ; i < sums.Length ; i++) {
sums[i] = sums[i-1] + values[i];
}
If all values are positive, you can run binary search on sums to get to the index in O(log(n)).
learn BST, it's will the fastest algo for your problem:
http://en.wikipedia.org/wiki/Binary_search_tree

adding two int array

I have to add two int[] array in which a mian int[] array is intially vacant. I want to add the elements of another array in the main array . In the Main array, there would be more addtion that would be added in the last postion of the main array.
I have an array as -
var planetNotInRange = new int[7] ;
if(planetSign.Contains(tempFrind))
{
var result = planetSign.Select((b, k) => b.Equals(tempFrind) ? k : -1)
.Where(k => k != -1).ToArray();
// Here I want to add this result Array in to the planetNotInRange array,
// when ever there is some value in the result array.
}
this is in loop will give a number of array of integers. Now I want to concat in PLanetInRange Array one after other.
It sounds like you shouldn't have an array to start with, if you want to add elements to it. Once an array has been created, its size is fixed.
Use a List<int> instead, and you can use
list.AddRange(array);
I'd usually advise using lists (and other collection types) over arrays anyway. Arrays are useful, obviously, but they're somewhat more primitive and low-level than other collections.

Categories