I need to read a line in a file.
Based on the first 3 characters in the file, I can determine a type of record.
This indicates the number of strings the line needs to be split into.
I need to hold all lines of the same type in a List.
How do I do this?
My sample file would look like
123|gf|hf|gr|9
145*gf*43*434*9*645*554
123|grf|fe|yr|9
So all 123 would be in a list of string array type of length 4 like :
public List<string[]> NTE =new List<string[4]>();
Except declaring a length isn't being accepted by the compiler
You could use
List<string[]> NTE =new List<string[]>();
And then as you need to add an element to the NTE, you only need to specify that the size will be 4:
NTE.Add(new string[4]); //here it is defined having size of 4, not in the list declaration
Then when you use it:
NTE[0] = ...something
That is going to be a string[4] array
class ArrayofFour
{
string[] a = new string[4];
public string this[int i]
{
get
{
return a[i];
}
set
{
a[i] = value;
}
}
}
Use the ArrayofFour instead of an array, you can use it like an array using the indexers. This will take care of validation you need.
Then you can have a List<ArrayofFour> NTE = new List<ArrayofFour>();
I think this is what you need or at least help you get there.
Related
Help me find out how to add the full array i created into one line, It looks like by changing the int to double to big error changes, so for now I just want to try to add everything on the whole line.
It seems when i try to add a array it prints out the name of the array, when i try to print out the array instance name it prints the file pathway, when i add split array[0] it successfully prints the first element in the array. How can I add the whole array and not just the first element?
This is what the text looks like:
regular,bread,2.00,2
regular,milk,2.00,3
This is what I want it to look like after coded
regular,bread,2.00,2,(the result of 2*2*GST)
regular,milk,2.00,3,(the result of 2*3*GST)
This is what I get it(dont need to show regular item cost string):
System.Collections.Generic.List`1[System.String]
RegularItemCost:
4.4
This is the code I have got for reading and the method and constructors for calculations:
public List<string> readFile()
{
string line = "";
StreamReader reader = new StreamReader("groceries.txt"); //variable reader to read file
while ((line = reader.ReadLine()) != null) //reader reads each line while the lines is not blank, line is assigned value of reader
{
line = line.Trim(); //gets rid of any spaces on each iteration within the line
if (line.Length > 0) //during each line the below actions are performed
{
string[] splitArray = line.Split(new char[] { ',' }); //creates a array called splitArray which splits each line into an array and a new char
type = splitArray[0]; // type is assigned for each line at position [0] on
name = splitArray[1]; //name is assigned at position [1]
//<<<-------food cost calculation methods initialized-------->>>>
RegularItem purchasedItem = new RegularItem(splitArray); //purchased Item is the each line to be printed
FreshItem freshItem = new FreshItem(splitArray);
double regCost = purchasedItem.getRegularCost(); //regCost will multiply array at position [2] with [3]
double freshCost = freshItem.getFreshItemCost();
string[] arrayList = { Convert.ToString(regCost), Convert.ToString(freshCost) };
List<string> newArray = new List<string>(splitArray);
newArray.AddRange(arrayList);
if (type == "regular")
{
// items.InsertRange(4, (arrayList)); //first write a line in the list with the each line written
items.Add(Convert.ToString(newArray));
items.Add("RegularItemCost:");
items.Add(Convert.ToString(regCost)); //next add the regCost method to write a line with the cost of that item
}
else if (type == "fresh")
{
items.Add(Convert.ToString(freshItem)); //first write a line in the list with the each line written
items.Add("FreshItemCost:");
items.Add(Convert.ToString(freshCost)); //next add the fresh method to write another line with the cost of that item
}
}
}
return items;
}
//constrctor and method
public class RegularItem : GroceryItem //inheriting properties from class GroceryItem
{
private string[] splitArray;
public RegularItem()
{
}
public RegularItem(string[] splitArray) //enables constructor for RegularItem to split into array
{
this.type = splitArray[0];
this.name = splitArray[1];
this.price = double.Parse(splitArray[2]); //each line at position 4 is a double
this.quantity = double.Parse(splitArray[3]); //each line at position 3 is parsed to an integer
}
public double getRegularCost() //method from cost of regular
{
return this.price * this.quantity * 1.1; //workout out cost for purchases including GST
}
}
Ok, multiple things. First, while it's not bad to use Convert. ToString(), i think is better to just do . ToString. Remember all objects inherit from object so all objects will have that method.
If you want all the values of a collection to be "joined" into one string beter use string. Join(), look at it, you can specify a separatorto use between values. If you just use the Convert. ToString() directly on the list it just print the information about the list object itself, not the values inside the list.
Next, if you use ToString or Convert. ToString with a built-in type like int or double, it will print the number as a string, but if you do it with your custom object or simply with a more conplex object like List it will just print the type info. To solve this in your custom objects (like RegularItem f. I.) you must override the ToString() method an code there what you want to print when the method get called. So you can override the method and put there to print the cost dor example.
how to get direct value from a list that contain an array ?
hey guys ,
i want to directly get a certain value from a list that contain an array
List<int[]> myList = new List<int[]>();
myList.Add( new int[2] { 10, 11 } );
its clear for me to get this using foreach loop like
foreach ( int[] p in mylist)
console.write(p[0]);
i do want to retrive this single data using expression like list[0] for list of integers
thanks..
Your question is very unclear, but if you know the array index within the array, you can use:
int value = myList[listIndex][arrayIndex];
Effectively this is just doing:
int[] array = myList[listIndex];
int value = array[arrayIndex];
im not entirely sure what you mean . . .
it would look like a 2d array: myList[position of array in list][position of item in selected array]. this is because a list is generic container and the overloaded bracket operator will return the specific type (which in this case is an array), that then enables you to use the bracket again to refer to the items contained in the array.
the snipplet you wrote actually only iterates the first item foreach array in your list (was this on purpose)?
in essence, you kind of need 2 pieces of information unless you only want the first item in each list (position 0) in which case you would create a new container class, implement the IList interface and overload the bracket operator like this:
public int this[int index]
{
get
{
return myList[index][0];
}
set
{
myList[index][0] = value;
}
}
I need to create a multidimensional guard List three values, X, Y and Z, and I need a List that is because once the value is queried, the array must be removed.
The query would look something like this: List [0] [0] = X, List [0] [a] = Y and List [0] [2] = X, so that I can remove only the index 0 and he already remove all the other three.
If you need to create a multidimensional list, you can always create a list of lists like so:
var multiDimensionalList = new List<List<string>>{
new List<string>{"A","B","C"},
new List<string>{"D","E","F"},
new List<string>{"G","H","I"},
};
Console.WriteLine(multiDimensionalList[2][1]); // Prints H
multiDimensionalList[2].RemoveAt(1);
Console.WriteLine(multiDimensionalList[2][1]); // Prints I
multiDimensionalList[2][1] = "Q";
Console.WriteLine(multiDimensionalList[2][1]); // Prints Q
Be aware though that attempting to replace a value that doesn't exist by way of assignment will throw an exception:
multiDimensionalList[2][5] = "R"; // Throws an ArgumentOutOfRangeException
Your question is very hard to understand, but perhaps what you are looking for can be accomplished with an array of arrays? This is how multidimensional arrays are implemented in some languages anyways.
In your case you might be using a List of List's: List>. And this would satisfy your requirement to remove "all the other three" by removing the first element in the outer List<> object.
I'm sorry but your question is a little bit hard to understand, but I will take a stab at it. Please don't interchange the words Array and List as they are different yet related ideas in C#. I believe that you mean Array with your use of [] brackets. Although you might want to consider using lists as they have a nice way to remove certain elements from a list by using the element. the MSDN has some good information as to how you might proceed.
List(T).Remove method
the list will restructure it self to remove or add elements as desired.
I am not sure I am following your logic as you are using both strings and integers as your second indexer, and referencing X twice, but not Z. Assuming these are typos, I am going to take a guess at what you want.
Have you considered a custom type with X, Y, AND Z properties, and an indexer to give you the behavior you described:
You also don't mention what types your values are, so I am using object, but feel free to substitute your own type (or a generic type)
public class MyType
{
private object[] backingArray = new object[3];
public object this[int index]
{
get { return backingArray[index]; }
set { backingArray[index] = value; }
}
public object X
{
get { return backingArray[0]; }
set { backingArray[0] = value; }
}
public object Y
{
get { return backingArray[1]; }
set { backingArray[1] = value; }
}
public object Z
{
get { return backingArray[2]; }
set { backingArray[2] = value; }
}
}
You could then use it like this:
List<MyType> list = new List<MyType>();
list = PopulateList(); // fill list with values
var x = list[0][0];
var y = list[0][1];
var z = list[0][2];
Of course, this implementation depends on your 2nd dimension always consisting of 3 elements. If it will not be consistent, then one of the other answers abound for your needs.
I have an array:
String[] ay = {
"blah",
"blah number 2"
"etc" };
... But now I want to add to this array at a later time, but I see no option to do so. How can this be done? I keep getting a message saying that the String cannot be converted to String[].
Thank you
Use a List rather than an array:
List<string> list = new List<string>();
list.Add( "blah" ) ;
Then, later, if you really do need it as an array:
string[] ay = list.ToArray();
Arrays are of fixed size, so after it has been created, you can't change the size of it (without creating a new array object)
Use the List<string> instead of the array.
Arrays can't change their size after they are declared. Use collections instead. For example: List.
As everyone's already said, use List in the System.Collections.Generic namespace.
You could also use a Hashtable which will allow you to give each string a meaning, or "key" which gives you an easy way to pull out a certain string with a keyword. (as for keeping messages stored in memory space for whatever purpose.)
You could also Create a new array each time you add a value, make the new array 1 bigger than the old one, copy all the data from the first array into the 2nd array, and then add your new value in the last slot (Length - 1)
Then replace the old array with your new one.
It's the most manual way of doing it.
But List and Hashtable work perfectly well too.
If you don't need indexing a specific array element (usage of brackets), but you want to be able to efficiently add or remove elements, you could use LinkedList.
If you do need indexing
have a look at Dictionary data type also in the System.Collection
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
so you could do something like
Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(1, "afljsd");
You can do this but I don't recommend it:
// Reallocates an array with a new size, and copies the contents
// of the old array to the new array.
// Arguments:
// oldArray the old array, to be reallocated.
// newSize the new array size.
// Returns A new array with the same contents.
public static System.Array ResizeArray (System.Array oldArray, int newSize) {
int oldSize = oldArray.Length;
System.Type elementType = oldArray.GetType().GetElementType();
System.Array newArray = System.Array.CreateInstance(elementType,newSize);
int preserveLength = System.Math.Min(oldSize,newSize);
if (preserveLength > 0)
System.Array.Copy (oldArray,newArray,preserveLength);
return newArray;
}
Here's an extension method to add the to arrays together and create a new string array
public static class StringArrayExtension
{
public static string[] GetStringArray (this string[] currentArray, string[] arrayToAdd)
{
List<String> list = new List<String>(currentArray);
list.AddRange(arrayToAdd);
return list.ToArray();
}
}
How is an array of string where you do not know where the array size in c#.NET?
String[] array = new String[]; // this does not work
Is there a specific reason why you need to use an array? If you don't know the size before hand you might want to use List<String>
List<String> list = new List<String>();
list.Add("Hello");
list.Add("world");
list.Add("!");
Console.WriteLine(list[2]);
Will give you an output of
!
MSDN - List(T) for more information
You don't have to specify the size of an array when you instantiate it.
You can still declare the array and instantiate it later. For instance:
string[] myArray;
...
myArray = new string[size];
You can't create an array without a size. You'd need to use a list for that.
you can declare an empty array like below
String[] arr = new String[]{}; // declare an empty array
String[] arr2 = {"A", "B"}; // declare and assign values to an array
arr = arr2; // assign valued array to empty array
you can't assign values to above empty array like below
arr[0] = "A"; // you can't do this
As others have mentioned you can use a List<String> (which I agree would be a better choice). In the event that you need the String[] (to pass to an existing method that requires it for instance) you can always retrieve an array from the list (which is a copy of the List<T>'s inner array) like this:
String[] s = yourListOfString.ToArray();
I think you may be looking for the StringBuilder class. If not, then the generic List class in string form:
List<string> myStringList = new List<string();
myStringList.Add("Test 1");
myStringList.Add("Test 2");
Or, if you need to be absolutely sure that the strings remain in order:
Queue<string> myStringInOriginalOrder = new Queue<string();
myStringInOriginalOrder.Enqueue("Testing...");
myStringInOriginalOrder.Enqueue("1...");
myStringInOriginalOrder.Enqueue("2...");
myStringInOriginalOrder.Enqueue("3...");
Remember, with the List class, the order of the items is an implementation detail and you are not guaranteed that they will stay in the same order you put them in.
I suppose that the array size if a computed value.
int size = ComputeArraySize();
// Then
String[] array = new String[size];
Can you use a List strings and then when you are done use strings.ToArray() to get the array of strings to work with?
If you will later know the length of the array you can create the initial array like this:
String[] array;
And later when you know the length you can finish initializing it like this
array = new String[42];
If you want to use array without knowing the size first you have to declare it and later you can instantiate it like
string[] myArray;
...
...
myArray=new string[someItems.count];
string[ ] array = {};
// it is not null instead it is empty.
string foo = "Apple, Plum, Cherry";
string[] myArr = null;
myArr = foo.Split(',');