index out of range checker not working - c#

So I would only like to assign the value to 'originalCOlumName' if there is a value in dataStore.DataSourceDef.Rows[columnIndex].ItemArray[3].ToString(); if it is NULL or out of range, doesnt exist etc...I want to skip this part.
Ive tried looking at another example on Preventing Index Out of Range Error
but NULL checkers didnt work also tried
if(string.IsNullOrEmpty(dataStore.DataSourceDef.Rows[columnIndex].ItemArray[3].ToString())

You would need to check the length of both the Rows and the ItemArray collections to ensure they have enough elements to index into... Remembering that to get element number 3, the array must contain 4 items since numbering starts at 0. This would look something like;
var rowsLength = dataStore.DataSourceDef.Rows.Count;
if (rowsLength >= columnIndex + 1){
var itemArrayLength = dataStore.DataSourceDef.Rows[columnIndex].ItemArray.Count;
if (itemArrayLength >= 4){
var theString = dataStore.DataSourceDef.Rows[columnIndex].ItemArray[3].ToString();
}
}

Related

C# string.split on readline not producing expected array length

Hi guys just carrying on working on my first app, done mainly to learn and nothing else. I want the user to be able to type in 2d6+4 OR 2d6, you should be able to substitute those numbers for any number. I'm getting errors parsing the information and I think it has something to do with the array containing more or less values than I anticipated, or it for some reason left the delimiter in. typing 2d6+4 or 2d6 +4 works fine, 2d6 however does not, which is what I thought the if statement should guard against. Any ideas?
Console.WriteLine("Please type the roll you would like to perform, for example - 2d6+4");
var rollLine = Console.ReadLine();
var diceLine = rollLine.Split(new Char[] { 'd', '+' }, StringSplitOptions.RemoveEmptyEntries);
diceCount = int.Parse(diceLine[0]);
diceType = int.Parse(diceLine[1]);
if (rollLine.Length > 2)
{
bonus = int.Parse(diceLine[2]);
}
else
{
bonus = 0;
}
It looks like you are just using the wrong variable for the length comparison. You are comparing the length of the string, not the length of the split array. It should be:
if (diceLine.Length > 2)
When user entered "2d6", the string length is 3, i.e. following rule is true
if (rollLine.Length > 2)
However, as per your logic you will get array of 2 items in the diceLine, i.e. diceLine[0] and diceLine[1] but after condition with length you call diceLine[2] that does not exist.
I.e. either change condition to
if (rollLine.Length == 5) // 2d6+4
or check for the length of the array
if (diceLine.Length > 2)
You want your IF to check if the rollLine length is greater than 3, not 2.
As the smallest thing you'll type in is, for example, 2d6, you want to check for the bonus only when the rollLine is more than 3 characters.
if (rollLine.Length > 3)
{
bonus = int.Parse(diceLine[2]);
}

Check a condition in list except for last entry using linq c#

I have a list contains
List<decimal> number= new List<decimal>();
number.Add(1);
number.Add(0);
number.Add(1);
Need to check if number list contains any values greater than 0 except for the last entry/list node using LINQ
test case
1
1
0 => false
0
0
1 =>true
I had tried something like this
number.Where(s => s > 0).Skip(number.Count).Any()
which will returns a boolean value. But this line of code always returns false .
Instead of removing value from the original list, you can skip last value by considering only (number.Count-1) values for processing. For eg.
List<decimal> number= new List<decimal>();
number.Add(1);
number.Add(0);
number.Add(1);
var exists = number.Take(number.Count-1).Any(x => x > 0);
If you NuGet Microsoft's Interactive Extensions with the ID "System.Interactive" - then you can do this:
var result = number.SkipLast(1).Where(x => x > 0).Any();
Skip will skip the number of objects in the sequence and not the object at the specified index.
Here you are skipping all the objects in the sequence and asking if there are any. So it returns false always(Assuming variable defaultdata in your example is typo for variable number).
Try this.
var res = number.Where((num, index) => index != number.Count - 1 && num > 0).Any();
Note: I do not have enough reputation points to comment as I'm new to StackOverFlow. Let me know if this answers your question.
So as I understand from "to check if number list contains any values greater than 0 except for the last entry/list node using LINQ" you don't want to check last value, so just remove it from list and check other items:
List<decimal> number= new List<decimal>();
number.Add(1);
number.Add(0);
number.Add(1);
number.RemoveAt(number.Count - 1);
var exists = number.Any(x => x > 0);
Or if you want to check only last element:
number.Take(number.Count-1).Any(x => x > 0).Dump();

c# list index 0 showing value as -1

I am creating a basic program in unity where I check a list array index carry out a certain action depending on the value, I then increment the index.The problem I am having is that the array always stores in index 0 and always equals -1.
public class numGen(){
int val;
int i = 0;
System.Random rnd = new System.Random();
val = rnd.Next(1, 5);
arrayList.Add(val);
Debug.Log("val"+val);
Debug.Log("array"+arrayList.IndexOf(i));
if (arrayList.IndexOf(i) == 1)
{
Debug.Log("action1");
i++;
}
else if (arrayList.IndexOf(i) == 2)
{
Debug.Log("action2");
i++;
}
//and so on
}
I have used debug in the log, so val will output a expected value, e.g. 2, gets added into the array when I check the value stored in the index it's -1.
Not sure how or why the int value is changing.
The problem here is a misunderstanding how ArrayList and IndexOf() works.
ArrayList.IndexOf()
Searches for the specified Object and returns the zero-based index of the first occurrence within the range of elements in the ArrayList that starts at the specified index and contains the specified number of elements.
So your exception comes from:
The zero-based index of the first occurrence of value within the range of elements in the ArrayList that starts at startIndex and contains count number of elements, if found; otherwise, -1.
I think your are looking for something like this:
ArrayList.Item()
Gets or sets the element at the specified index.
Also it's possible to
This property provides the ability to access a specific element in the collection by using the following syntax: myCollection[index].
An example in your case:
if (arrayList[i] == 1)
{
// if true..
}
arrayList.IndexOf(i) gives the index of any element with the value of i. If you want the value at index i, you must use arrayList[I] instead.
IndexOf gives the index of the value you give. If there is no equal value found in the array it returns -1
ArrayList arr = new ArrayList();
arr.Add(5);
arr.Add(2);
var isMinusOne = arr.IndexOf(0); //Is -1
var isZero = arr.IndexOf(5); //Is 0

Loop to Check if Index Has Repeated in C#

I would like to create a for loop to check if an index value has repeated, and if it has to remove it from the original and display an updated list with no repeated index values.
I have and Array (called Original) with multiple values being repeated, and then I created a Temporary Array (called TempArray) with the same exact values.
I want to check the Original and TempArray values against each other to see if there are duplicates.
I want my code to be similar to a previous one I did where I deleted an index from the middle of my array, as follows
for (int i = 0; i < Original.Length; i++)
{
TempArray[i] = Original[i];
}
Original = new int[Original.Length - 1];
//Set index to delete
int DeleteIndex = 3;
//modify size of Orignial array and copy in array without deleted element index
for (int i = 0; i < TempArray.Length; i++)
{
if (i < DeleteIndex)
{
Original[i] = TempArray[i];
}
else if (i > DeleteIndex)
{
Original[i - 1] = TempArray[i];
}
}
P.S. Original[] is an array from a text file. Sorry if my explanation is hard to understand as I am new to computer programming.
Also is there any way to do this code without LINQ, I have to create using arrays only as its all thats been taught at school?
It took some time to understand what you want :)
to check if an index value has repeated, and if it has to remove it from the original and display an updated list with no repeated index values
It is shortly called distinct values. There is a LINQ method .Distinct():
Original = Original.Distinct().ToArray();
It will remove all repeated values.
where I deleted an index from the middle of my array
You can do this easier by converting to List, applying RemoveAt and back:
var list = new List<int>(Original);
list.RemoveAt(DeleteIndex);
Original = list.ToArray();
P.S. Assuming that you say "index" about the values in your array, it is pretty confusing. Array does not store indices - index is usually understood as a key of an array.
May be this will do the trick for you. I am assuming that you need to remove duplicate from your array
Original = Original.Distinct().ToArray();
Will Returns distinct elements from a sequence by using the default equality comparer to compare values.

How to retrieve the values from list using indexes by linq query?

I have a list of int that contains 5,6,7,8,5,4,3. I like to retrieve the value from list using their index. For example, I give start index as 1 and end index 4 I will get 6,7,8,5 in new list. How can I do this in Linq?
Use Skip and Take:
var results = list.Skip(1).Take(4);
EDIT: Note that it's not clear from your question exactly what limits you're using. If you're trying to be inclusive on both ends, using 0-based indexing, you want:
var results = list.Skip(startIndex).Take(endIndex - startIndex + 1);
Note that this won't let you get 0 results though - you may want to make endIndex exclusive so that if it equals startIndex, you get nothing. Then the code is:
var results = list.Skip(startIndex).Take(endIndex - startIndex);
Or an alternative approach is to use them the other way round. For example, the last snippet above is equivalent to:
var results = list.Take(endIndex).Skip(startIndex);
this may work for you:
list.Where((l, index) => index >= 1 && index <= 4 )

Categories

Resources