How can this row give back -1 in index? i have no clue how. there is none of em that can have -1 in index all of them are lists? The lists have values 148, 2999, 620
products.prestaShopCategoryId2.Add(categories2.CategoryPrestaId[categories2.NewCategoryId.FindIndex(a => a.Contains(products.productCategoryId2[j]))]);
I'd suggest you to refactor this code, as it is very hard to read and problems like the one you have becaome very hard to solve. Please, see below code:
var indexOfItem = categories2.NewCategoryId.FindIndex(a => a.Contains(products.productCategoryId2[j]));
// Here you can handle situation, when element is not found and
// returned index is -1
if(indexOfItem == -1)
throw new Exception("Item not found!");
var itemToAdd = categories2.CategoryPrestaId[indexOfItem];
products.prestaShopCategoryId2.Add(itemToAdd);
Additionally, you add some logging along the way or anything that will make your life easier, etc.
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.findindex?view=netframework-4.8
Returns Int32 The zero-based index of the first occurrence of an
element that matches the conditions defined by match, if found;
otherwise, -1.
When not found, it is -1.
Related
so my problem is that I don't know how to go forward in the list and print the next same integer if there is one.
Here is what I have at the moment:
while (list.Contains(input1))
{
Console.WriteLine(input1 + " is at index " + list.IndexOf(input1))
}
I am trying to list all of the integers that are in the list and print the index of them. But not remove after finding one of the integers (this was at least my first idea.).
IndexOf has an overload with two parameters, which allows you to start searching at a later position in the list.
Since this is obviously a learning exercise, I won't spoil it by providing the full code, but rather suggest that you try to implement the following algorithm:
Find the index of input starting at position 0.
If not found (i.e., IndexOf returns -1): we're done. Otherwise:
Print and remember that index.
Start again at step 1, but this time, don't start searching at 0 but at the index you remembered + 1.
You can do the following:
go through the list/array using for statement
for(int i=0; i < list.length; i++) // loop though list
then inside the loop check the value of the current item using if statement:
if(list[i] == input1)
//do smothing
The list[0] represent the first item in the array, which means the index is 0.
so in the example above the i will be the current index so long that you in the loop.
I didn't write the full code for learning purpose in reference to #Heinzi answer.
Hope that could be helpful!
This is an implementation possibility. It is longer than it has to be, but it makes it clearer for beginners how one could tackle this problem.
Since you wanted to only show numbers that come up more than once here is an implementation method. If you want to show numbers that come up only once too just erase everything about lastindex
List<int> yourlist = new List<int> { 1,1,1,1,1,11,2,3,3,4,4,5 };
int input = 0;
input = Convert.ToInt32(Console.ReadLine());
var index = yourlist.IndexOf(input);
//this checks if your input is in the list
var lastindex = yourlist.LastIndexOf(input);
//this does the same but it searches for the last implementation of your input
if (index != -1 && lastindex != index)
//this if checks if your number comes up more than once. IndexOf returns -1 if there is no occurence of your input
{
Console.Write($"the index of {input} is {index}");
for (int i = index+1; i <= yourlist.Count; i++)
//this loop takes the position of the first occurence of your number and then counts up from there
{
var tempindex = yourlist.IndexOf(input, i);
if (tempindex != -1)
//this if lets everything except -1 through
{
Console.Write($" and {tempindex}");
}
}
}
else
{
Console.WriteLine("your number cannot be found twice in the list");
}
I have listview with 3 items and 1 subitems
So I would like to check if a row on item[3] is String.Empty.
if items[3] is empty it will not pass my items[3] to label1.Text.
if items[3] is not empty it will pass my items[3] to my label1.Text
.
this is my code
if (listView1.Items[3].SubItems[1].Text == string.Empty)
{
label1.Text = "";
}
else
{
label1.Text = listView1.Items[3].SubItems[1].Text;
}
when my 3rd row is empty I got an error: InvalidArgument=Value of '3' is not valid for 'index'.
so how do i check the row if its empty and what validation should i do if it's empty i will not pass my items to label1.Text and if its not empty it will pass the Items to label1.Text
You have 3 items, So the maximum index is 2 because the index of the array count from 0.
Same principle for the subitem.
Use Items[2] and SubItems[0]
if (listView1.Items[2].SubItems[0].Text == string.Empty)
Indexes in C# start at 0, so a collection that has 3 items would have the indexes of 0, 1 and 2. Based on your question, your if statement should look like this:
if (listView1.Items[2].SubItems[0].Text == string.Empty)
When trying to access something by its index you should typically have some sort of safety check, like checking the .Length or .Count before attempting to access something that could be out of range. You can also leverage some Linq and the null conditional operator to make things a little safer (albeit slightly slower since its enumerating):
//Skip 2, take the 3rd if its there then take the first SubItem.
//label1.Text is either the text or an empty string
label1.Text = listView1.Items.Skip(2).FirstOrDefault()?.SubItems
.FirstOrDefault()?.Text ?? string.Empty;
i have this code:
ArrayList list = new ArrayList();
foreach (DataRow dataR in prenume.Rows)
{
foreach (var item in dataR.ItemArray)
{
if (item.Equals(" ")) continue;
list.Add(item);
if (input_string.Equals(item.ToString()) && list.Count > 0 )
{
label_hello.Text = "Hello, " + list[2];
}
}
}
When i'm trying to clear the text showed , i get an error which says:
Index was out of range. Must be non-negative and less than the size
of the collection.
Later edit:
Solution found!I was too tired ... sorry for the question!
Well, you start off with an empty list, and then after adding a single item, you might execute (if input_string equals the first item in the first item array):
label_hello.Text = "Hello, " + list[2];
That's trying to access the third item in the list. It will fail when there's only one item. Why did you pick 2 here?
(As an aside, why are you using ArrayList? The generic List<T> type is preferred.)
It's not clear what you're trying to achieve - if you can give us more context, we have a better chance of helping you.
EDIT: From the comments, it looks like this should be
label_hello.Text = "Hello, " + dataR[2];
However, I suspect the loops are still not right... why would you want to iterate over every value in the table, rather than (say) in just one column?
Ofcourse it will give an error.
label_hello.Text = "Hello, " + list[2];
is wrong.
You have only one element list[0] at that stage.
you're getting your error on the following line
label_hello.Text = "Hello, " + list[2];
The reason why you're getting that error is because there is no list[2]
Now, I can't tell exactly what you're trying to do, but I have a sneaky suspicion that you intend 'item' to be a string of some sort, and you want to access the third character in that string.
Even then, keep in mind that sometimes the user might try to input a string that is not 3 or more characters in length.
If you can give more details about what you're trying to do, we can help you further.
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];
I am confused about the BinarySearch method of List<T> in case when the item does not exist.
I've got
List<long> theList = {1, 3, 5, ...}.
theList.BInarySearch(0) returns 0, and theList.BInarySearch(3) returns 1, as expected.
However, theList.BinarySearch(1) returns -2, and not -1 as I'd expect. The MSDN manual says:
"Return value: The zero-based index of item in the sorted List, if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count."
A "bitwise complement"? What Am I missing here and why is it that theList.BinarySearch(1) != -1 ?
I assume you are talking about theList.BinarySearch(2), because 1 exists and the return value should be 0.
The bitwise complement operator does not produce the same effect as negating the integer, which I think is the source of your confusion. In any case, you do not need to understand how the operator works to accurately branch on the search-result; the MSDN paragraph in your question, and the fact that ~~a = a, directly implies this snippet:
int index = theList.BinarySearch(num);
if (index >= 0)
{
//exists
...
}
else
{
// doesn't exist
int indexOfBiggerNeighbour = ~index; //bitwise complement of the return value
if (indexOfBiggerNeighbour == theList.Count)
{
// bigger than all elements
...
}
else if (indexOfBiggerNeighbour == 0)
{
// smaller than all elements
...
}
else
{
// Between 2 elements
int indexOfSmallerNeighbour = indexOfBiggerNeighbour - 1;
...
}
}
First - why would you expect -1? If the item is the first item, it cannot return -0 (for integers), so it stands to reason -2 will be returned for the second item.
Next, you can easily get the right index by using ~-2 - the bitwise not operator.
The reason for returning these negative indices is to support inserting items that are not found into the list. In this example, 2 would be inserted at index = 2. Otherwise, you would have to perform another binary search to find that position.
To transform it to an insertion point, take the bitwise complement, that is: ~retval