Modifying values within a list - c#

I've been trying to write a program which can scan a raw data file and normalize it for data mining processes, I've trying to read the data from the file and store it in a list this way:
public static List<Normalize> NF()
{
//Regex r = new Regex(#"^\d+$");
List<Normalize> N = new List<Normalize>();
StreamReader ss = new StreamReader(#"C:\Users\User\Desktop\NN.txt");
String Line = null;
while (!ss.EndOfStream) {
Line = ss.ReadLine();
var L = Line.Split(',').ToList();
N.Add(new Normalize { age = Convert.ToInt16(L[0]),
Sex = L[1],
T3 = Convert.ToDouble(L[2]),
TT4 = Convert.ToDouble(L[3]),
TFU = Convert.ToDouble(L[4]),
FTI = Convert.ToDouble(L[5]),
RC = L[6],
R = L[7]
});
}
return N;
}
}
struct Normalize {
public int age;
public String Sex;
public double T3;
public double TT4;
public double TFU;
public double FTI;
public String RC;
public String R;
}
At this moment I want to go through the list that I've made and categorize the data , similar to this :
var X= NF();
for (int i = 0; i < X.Count; i++) {
if (X[i].age > 0 && X[i].age <= 5) { // Change the X[i].age value to 1 }
else if (X[i].age > 5 && X[i].age <= 10) { // Change the X[i].age value to 2 }
...
}
But the compiler says X[i].[variable name] is not a variable and cannot be modified in this way. My question is, what would be an efficient way to perform this operation.

struct Normalize is a value type, not a reference type, therefore you cannot change its fields like that. Change it to class Normalize

Change struct Normalize to class Normalize and iterate with foreach loop. It's way cleaner.
You could also set variables to private and use getters/setters to check/set variable.
foreach (Normalize x in X)
{
if (x.getAge() > 0 && x.getAge() <= 5)
x.setAge(1)
...
}
Edit:
just saw you already got your answer

Modifying struct field is fine as long as it's a single entity (Given its a mutable struct). This is possible -
var obj = new Normalize();
obh.Age = 10;
But in your case you are accessing the struct using indexer from the list.
Indexer will return copy of your struct and modifying the value won't reflect it back to the list which ain't you want.
Hence compiler is throwing error to stop you from writing this out.
As Alex mentioned, you should go for creating class instead of struct if you want to modify it.
On a side note, its always advisable to have immutable structs instead of mutable structs.

Related

How to access a Object property, in a List of generated Objects

I searched the heck out of it, and i can't solve it.
I have a program setup like this (it's in Unity and Visual Studio 2019 for C#):
Note that the CSV loading goes fine, when i debug the code i can see everything filled with corect data.
#region character class
public class _Character
{
public int Id { get; set; }
public int Variation { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
#endregion
//Tools.LoadCsv generates a string[,] from a csv file
//Tools.IntParse parses int's with a lot of format error checking
void Start()
{
#region load characters class
string[,] CharacterCSV = Tools.LoadCsv(#"Assets/GameDB/character.csv");
List<_Character> Character = new List<_Character>();
for (int i = 1; i < CharacterCSV.GetUpperBound(0); i++)
{
_Character temp = new _Character();
temp.Id = Tools.IntParse(CharacterCSV[i, 0]);
temp.Variation = Tools.IntParse(CharacterCSV[i, 1]);
temp.Name = CharacterCSV[i, 2];
temp.LastName = CharacterCSV[i, 3];
Character.Add(temp);
}
CharacterCSV = null;
#endregion
}
I barely understand objects, so i'm sorry if i am doing it wrong.
The questions i have are:
Why does the Object List generation Háve to be in Start ? I can't seem to do that in it's own class.
How can i get an object from the Character Object List, containing Id = 100 and Name = "John"
, and access it from another class or method.
I ussualy frankenstein the heck out of code and make it good enough for me, but now i wanted to make something nice and cant seem to get to the objects.
Thanks in advance!
//the major issue was declaring the object inside the class, when declared outside the class, the List Object was available to the outside world.
List<_Character> Character = new List<_Character>(); move to outside Start{}
I'm not editing the question to correct the code, because the question needs to stay clear.
//
Why does the Object List generation has to be in Start ? I can't seem to do that in it's own class.
How can i get an object from the Character Object List, containing Id = 100 and Name = "John" , and access it from another class or method.
If you want to retrieve a character from outside of the class, then, you have to declare the list outside of the Start function, otherwise, the list will be destroyed since it's a local variable of the function.
// Declare the list outside of the functions
private List<_Character> characters;
void Start()
{
// Avoid using regions, they encourage you to make very long functions with multiple responsabilities, which is not advised
// Instead, create short and simple functions, and call them
LoadCharactersFromCSV();
}
void LoadCharactersFromCSV()
{
string[,] CharacterCSV = Tools.LoadCsv(#"Assets/GameDB/character.csv");
// If you can, indicate the approximate numbers of elements
// It's not mandatory, but it improves a little bit the performances
characters = new List<_Character>( CharacterCSV.GetUpperBound(0) );
// I believe `i` should start at 0 instead of 1
for (int i = 1; i < CharacterCSV.GetUpperBound(0); i++)
{
// I advise you to create a constructor
// instead of accessing the properties one by one
_Character temp = new _Character();
temp.Id = Tools.IntParse(CharacterCSV[i, 0]);
temp.Variation = Tools.IntParse(CharacterCSV[i, 1]);
temp.Name = CharacterCSV[i, 2];
temp.LastName = CharacterCSV[i, 3];
characters.Add(temp);
}
CharacterCSV = null;
}
// Using this function, you will be able to get a character from its id
public _Character GetCharacter( int id )
{
for (int 0 = 1; i < characters.Count; i++)
{
if( characters[i].Id == id )
return characters[i];
}
// Return null if no character with the given ID has been found
return null ;
}
Then, to call GetCharacter from another class:
public class ExampleMonoBehaviour : MonoBehaviour
{
// Replace `TheClassName` by the name of the class above, containing the `Start` function
// Drag & drop in the inspector the gameObject holding the previous class
public TheClassName CharactersManager;
// I use `Start` for the sake of the example
private void Start()
{
// According to your code, `_Character` is defined **inside** the other class
// so you have to use this syntax
// You can get rid of `TheClassName.` if you declare `_Character` outside of it
TheClassName._Character john = CharactersManager.GetCharacter( 100 );
}
}

Having an integer inside a method that increases by 1 everytime the method was called to a specific object of a lass

I have a 'Movie' class in my C# code that has an int[] ratings = new int[10]; as a field. I would like to place numbers in this empty array from my main program.
For that, I would need a method, that could point to the actual free index of the array to put the integer there, but the other integer that would point to the free index would be reset to 0 everytime the method is called. Thus, my question is, that how can I place an integer in my method that is increased everytime the method was called.
This is the method in the class:
public void Rate(int rating)
{
int x = 0;
ratings[x] = rating;
}
This is how I call it in the main program
Movie asd = new Movie(blabla...);
Rate.asd(1);
Rate.asd(1);
Rate.asd(1);
So I called it 3 times, and I would want the 'x' integer in the class's method to increase.
Thanks in advance.
First of all, you have an error in the code you have posted.
As I suppose rather than:
Movie asd = new Movie(blabla...);
Rate.asd(1);
Rate.asd(1);
Rate.asd(1);
you want to paste here:
Movie asd = new Movie(blabla...);
asd.Rate(1);
asd.Rate(1);
asd.Rate(1);
As C# does not allow to use static method variables (like i.e. C++ does) you have two options:
first, make x value (from Rate method) a Movie's class variable, so Rate method will "remember" the next index,
second (and better) rather than intiger array - if possible use any kind of list or queue (which can manage indexing for you).
The problem is that local variables are discarded when exiting a method.
class SomeClass
{
private int x = 42;
public void DoSometing(int y)
{
int a = y + 5;
x += a * a;
// a stops to exist here
}
}
Solution is to store the variable in the containing class as well
class SomeOtherClass
{
private int x = 42;
private int a = 0;
public void DoSomething(int y)
{
a = y + 5;
x += a * a;
}
}
Now SomeOtherClass remembers the value of a. That's basically the point of member variables a.k.a. fields - to store the state of the object.
More appropriate for your problem:
class ClassWithAnArrayAndCount
{
private int[] values = new int[10];
private int taken = 0;
public void Add(int value)
{
if (taken == 10)
throw new ArgumentOutOfRangeException(); // sorry, no more space
values[taken++] = value;
}
public int Taken { get { return taken; } }
}

C#: Immutable class

I have a class which should be immutable in this class i have only get indexer a private set property so why this is not immutable and i can set some field in array as you could see in main class...
class ImmutableMatice
{
public decimal[,] Array { get; private set; } // immutable Property
public ImmutableMatice(decimal[,] array)
{
Array = array;
}
public decimal this[int index1, int index2]
{
get { return Array[index1, index2]; }
}
........
and in main method if i fill this class with data and change the data
static void Main(string[] args)
{
decimal[,] testData = new[,] {{1m, 2m}, {3m, 4m}};
ImmutableMatice matrix = new ImmutableMatice(testData);
Console.WriteLine(matrix[0,0]); // writes 1
testData[0, 0] = 999;
Console.WriteLine(matrix[0,0]); // writes 999 but i thought it should
// write 1 because class should be immutable?
}
}
Is there any way how to make this class immutable?
Ah yes the solution was copy array to new array in constructor like this:
public ImmutableMatice(decimal[,] array)
{
decimal[,] _array = new decimal[array.GetLength(0),array.GetLength(1)];
//var _array = new decimal[,] { };
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
_array[i, j] = array[i, j];
}
}
Array = _array;
}
That is because you are actually changing the data in the ARRAY, rather than the indexer.
static void Main(string[] args)
{
decimal[,] testData = new[,] {{1m, 2m}, {3m, 4m}};
ImmutableMatice matrix = new ImmutableMatice(testData);
Console.WriteLine(matrix[0,0]); // writes 1
testData[0, 0] = 999; // <--- THATS YOUR PROBLEM
Console.WriteLine(matrix[0,0]); // writes 999 but i thought it should
// write 1 because class should be immutable?
}
You can copy the array into your private property in the constructor to avoid this situation.
Note that you indeed cannot write matrix[0,0] = 999; because the indexer has no setter.
Edit
As Chris pointed out (how could I have missed it myself?) - you shouldn't expose the array as a property at all (which means in most cases it doesn't even have to be a property).
Consider the following code instead:
private decimal[,] _myArray; // That's private stuff - can't go wrong there.
public decimal this[int index1, int index2]
{
// If you only want to allow get data from the array, thats all you ever need
get { return Array[index1, index2]; }
}
Your class is immutable, but the objects inside it aren't.
Having public decimal[,] Array { get; private set; } will only guarantee that you cannot set the property Array to a new instance of Array, but it does not prevent you from accessing the existing object and changing its values (which aren't immutable).
You might want to look into the appropriately named ReadOnlyCollection<T> class.
As #Mike pointed out and I looked past the first time: there's a twist to this because you are accessing the value through the testData object and not through matrix. While the original point still stands, it is more exact to say that the problem you have is that you are changing values in the underlying object which has its reference passed around. You're bypassing the ImmutableMatice object alltogether.
The beforementioned solution of using a ReadOnlyCollection<T> still stands: by creating this read-only wrapper around it, you won't be able to change it anymore afterwards. Howver this is only the case when you actually use it the way its intended: through ImmutableMatice and not through the underlying collection which you still have a reference to.
Another solution that solves this problem is to copy the contents of the original array to another one to "disconnect" it from the array your still have a reference to.
In order to illustrate this, consider the following samples. The first one demonstrates how the underlying reference can still be influenced while the second one shows how it can be solved by copying your values to a new array.
void Main()
{
var arr = new[] { 5 };
var coll = new ReadOnlyCollection<int>(arr);
Console.WriteLine (coll[0]); // 5
arr[0] = 1;
Console.WriteLine (coll[0]); // 1
}
void Main()
{
var arr = new[] { 5 };
var arr2 = new int[] { 0 };
Array.Copy(arr, arr2, arr.Length);
var coll = new ReadOnlyCollection<int>(arr2);
Console.WriteLine (coll[0]); // 5
arr[0] = 1;
Console.WriteLine (coll[0]); // 5
}

Need help converting this snippet from c to c#

typedef struct {
int e1;
int e2;
int e3;
int e4;
int e5;
} abc;
void Hello(abc * a, int index)
{
int * post = (&(a->e1) + index);
int i;
for(i = 0; i<5; i++)
{
*(post + i) = i;
}
}
The problem I face here is how they able to access the next element in the struct by
*(post + i)
I'm not sure how all these would be done in C# and moreover, I don't want to use unsafe pointers in C#, but something alternate to it.
Thanks!
You should replace the struct with an array of 5 elements.
If you want to, you can wrap the array in a class with five properties.
edit...
When you say 'Wrap,' it generally means to write properties in a class that set or get the value of either a single variable, an array element, or a member of another class whose instance lives inside your class (the usual usage here = 'wrap an object'). Very useful for separating concerns and joining functionality of multiple objects. Technically, all simple properties just 'wrap' their private member variables.
Sample per comment:
class test
{
int[] e = new int[5];
public void Hello(int index)
{
for (int i = 0; i <= 4; i++) {
// will always happen if index != 0
if (i + index > 4) {
MsgBox("Original code would have overwritten memory. .Net will now blow up.");
}
e[i + index] = i;
}
}
public int e1 {
get { return e[0]; }
set { e[0] = value; }
}
public int e2 {
get { return e[1]; }
set { e[1] = value; }
}
//' ETC etc etc with e3-e5 ...
}
The problem with the C code is that if index is greater than 0 it runs off the end of the abc struct, thus overwriting random memory. This is exactly why C#, a safer language, does not allow these sorts of things. The way I'd implement your code in C# would be:
struct abc
{
public int[] e;
}
void Hello(ref abc a, int index)
{
a.e = new int[5];
for (int i = 0; i < 5; ++i)
a.e[index + i] = i;
}
Note that if index > 0, you'll get an out of bounds exception instead of possibly silent memory overwriting as you would in the C snippet.
The thinking behind the C codes is an ill fit for C#. The C code is based on the assumption that the fields of the struct will be placed sequentially in memory in the order defined the fields are defined in.
The above looks like either homework or a contrived example. Without knowing the real intent it's hard to give a concrete example in C#.
other examples here suggest changing the data structure but if you can't/don't want to do that, you can use reflection combined with an array of objects of the struct type to accomplish the same result as above.
void Hello(abc currentObj){
var fields = typeof(abc).GetFields();
for(var i = 0;i<fields.Length;i++){
fields[i].SetValue(currentObj,i);
}
}

How can I find the last element in a List<>?

The following is an extract from my code:
public class AllIntegerIDs
{
public AllIntegerIDs()
{
m_MessageID = 0;
m_MessageType = 0;
m_ClassID = 0;
m_CategoryID = 0;
m_MessageText = null;
}
~AllIntegerIDs()
{
}
public void SetIntegerValues (int messageID, int messagetype,
int classID, int categoryID)
{
this.m_MessageID = messageID;
this.m_MessageType = messagetype;
this.m_ClassID = classID;
this.m_CategoryID = categoryID;
}
public string m_MessageText;
public int m_MessageID;
public int m_MessageType;
public int m_ClassID;
public int m_CategoryID;
}
I am trying to use the following in my main() function code:
List<AllIntegerIDs> integerList = new List<AllIntegerIDs>();
/* some code here that is ised for following assignments*/
{
integerList.Add(new AllIntegerIDs());
index++;
integerList[index].m_MessageID = (int)IntegerIDsSubstring[IntOffset];
integerList[index].m_MessageType = (int)IntegerIDsSubstring[IntOffset + 1];
integerList[index].m_ClassID = (int)IntegerIDsSubstring[IntOffset + 2];
integerList[index].m_CategoryID = (int)IntegerIDsSubstring[IntOffset + 3];
integerList[index].m_MessageText = MessageTextSubstring;
}
Problem is here: I am trying to print all elements in my List using a for loop:
for (int cnt3 = 0 ; cnt3 <= integerList.FindLastIndex ; cnt3++) //<----PROBLEM HERE
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\n", integerList[cnt3].m_MessageID,integerList[cnt3].m_MessageType,integerList[cnt3].m_ClassID,integerList[cnt3].m_CategoryID, integerList[cnt3].m_MessageText);
}
I want to find the last element so that I equate cnt3 in my for loop and print out all entries in the List. Each element in the list is an object of the class AllIntegerIDs as mentioned above in the code sample. How do I find the last valid entry in the List?
Should I use something like integerList.Find(integerList[].m_MessageText == null;?
If I use that it will need an index that will range from 0 to whatever maximum. Means I will have to use another for loop which I do not intend to use. Is there a shorter/better way?
To get the last item of a collection use LastOrDefault() and Last() extension methods
var lastItem = integerList.LastOrDefault();
OR
var lastItem = integerList.Last();
Remeber to add using System.Linq;, or this method won't be available.
If you just want to access the last item in the list you can do
if (integerList.Count > 0)
{
// pre C#8.0 : var item = integerList[integerList.Count - 1];
// C#8.0 :
var item = integerList[^1];
}
to get the total number of items in the list you can use the Count property
var itemCount = integerList.Count;
In C# 8.0 you can get the last item with ^ operator full explanation
List<char> list = ...;
var value = list[^1];
// Gets translated to
var value = list[list.Count - 1];
Lets get at the root of the question, how to address the last element of a List safely...
Assuming
List<string> myList = new List<string>();
Then
//NOT safe on an empty list!
string myString = myList[myList.Count -1];
//equivalent to the above line when Count is 0, bad index
string otherString = myList[-1];
"count-1" is a bad habit unless you first guarantee the list is not empty.
There is not a convenient way around checking for the empty list except to do it.
The shortest way I can think of is
string myString = (myList.Count != 0) ? myList [ myList.Count-1 ] : "";
you could go all out and make a delegate that always returns true, and pass it to FindLast, which will return the last value (or default constructed valye if the list is empty). This function starts at the end of the list so will be Big O(1) or constant time, despite the method normally being O(n).
//somewhere in your codebase, a strange delegate is defined
private static bool alwaysTrue(string in)
{
return true;
}
//Wherever you are working with the list
string myString = myList.FindLast(alwaysTrue);
The FindLast method is ugly if you count the delegate part, but it only needs to be declared one place. If the list is empty, it will return a default constructed value of the list type "" for string. Taking the alwaysTrue delegate a step further, making it a template instead of string type, would be more useful.
int lastInt = integerList[integerList.Count-1];
Though this was posted 11 years ago, I'm sure the right number of answers is one more than there are!
You can also doing something like;
if (integerList.Count > 0)
var item = integerList[^1];
See the tutorial post on the MS C# docs here from a few months back.
I would personally still stick with LastOrDefault() / Last() but thought I'd share this.
EDIT;
Just realised another answer has mentioned this with another doc link.
Change
for (int cnt3 = 0 ; cnt3 <= integerList.FindLastIndex ; cnt3++)
to
for (int cnt3 = 0 ; cnt3 < integerList.Count; cnt3++)
Use the Count property. The last index will be Count - 1.
for (int cnt3 = 0 ; cnt3 < integerList.Count; cnt3++)
Why not just use the Count property on the List?
for(int cnt3 = 0; cnt3 < integerList.Count; cnt3++)
Independent of your original question, you will get better performance if you capture references to local variables rather than index into your list multiple times:
AllIntegerIDs ids = new AllIntegerIDs();
ids.m_MessageID = (int)IntegerIDsSubstring[IntOffset];
ids.m_MessageType = (int)IntegerIDsSubstring[IntOffset + 1];
ids.m_ClassID = (int)IntegerIDsSubstring[IntOffset + 2];
ids.m_CategoryID = (int)IntegerIDsSubstring[IntOffset + 3];
ids.m_MessageText = MessageTextSubstring;
integerList.Add(ids);
And in your for loop:
for (int cnt3 = 0 ; cnt3 < integerList.Count ; cnt3++) //<----PROBLEM HERE
{
AllIntegerIDs ids = integerList[cnt3];
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\n",
ids.m_MessageID,ids.m_MessageType,ids.m_ClassID,ids.m_CategoryID, ids.m_MessageText);
}
I would have to agree a foreach would be a lot easier something like
foreach(AllIntegerIDs allIntegerIDs in integerList)
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\n", allIntegerIDs.m_MessageID,
allIntegerIDs.m_MessageType,
allIntegerIDs.m_ClassID,
allIntegerIDs.m_CategoryID,
allIntegerIDs.m_MessageText);
}
Also I would suggest you add properties to access your information instead of public fields, depending on your .net version you can add it like public int MessageType {get; set;} and get rid of the m_ from your public fields, properties etc as it shouldnt be there.

Categories

Resources