Store process output in array - c#

I initiated an empty array - line.
string[] line = new string[] { };
I want to store every line that would be outputed in a cmd processing with the while loop below. This seems to work easily if I store the values in a string variable.
As shown below:
while (!proc.StandardOutput.EndOfStream)
{
line = proc.StandardOutput.ReadLine();
}
However, I'm not sure how to store the values as separate elements in the array. I've tried:
while (!proc.StandardOutput.EndOfStream)
{
for(a in line)
{
a = proc.StandardOutput.ReadLine();
}
}
But its not working.
This is probably a very basic question. But I'm still learning C#.

There are few solutions. One would be to use List<string> instead of string[]:
List<string> line = new List<string>();
And than add lines next way:
while (!proc.StandardOutput.EndOfStream)
{
line.Add(proc.StandardOutput.ReadLine());
}

An array works on the basis of indexing. So if you want to use an array you need to specify how long it has to be or in other words how many items it can contain:
// this array can store 100 items
string[] line = new string[100];
To access a certain position you need to use the [ ] operator and to move forward in the array you need an indexing variable of type int that you can increment each iteration
int indexer = 0;
while (!proc.StandardOutput.EndOfStream)
{
line[indexer] = proc.StandardOutput.ReadLine();
indexer ++; // increment
}
This way you need to know in advance how many items you want to deposit in your array.
Another way would be to use a flexible collection like List which can dynamically grow. Sidenote: The indexing works with the same [ ] operator, but the adding of items works via the Add method
If you want to know more have look at this overview of possible collection types

Related

How to collect only selected indexed item's values from dictionary in C#?

I have a Dictionary contains Line and Dot classes.
Everyline that i found in LineList i add in dictiory 1st item and Dots inside that line to 2nd item.
I want to collect each Dots in one line and repeat it for every other line in dictionary.
public void collectingAllLines()
{
Dictionary<Line, Dot> TempDotsInLines = new Dictionary<Line, Dot>();
foreach (Line line in LinesList)
{
// Each line contains minimum 2 dots
foreach (Dot dot in DotsList)
{
if(line.DotIsOntheLine(dot) == true)
{
TempDotsInLines.Add(line, dot);
}
}
}
for (int i = 0; i < LinesList.Count; i++)
{
foreach(Dot dots in TempDotsInLines[Line[i]])
{
//I am trying to collect all dots in one line from TempDotsInLines dictionary.
// I want to turn in all lines in TempDotsInLine dictionary
}
}
}
You will not be able to put the same line in dictionary more than once. Dictionary is not what you want to use here.
It would help to see more of your code or have a better understanding of your end goal. But I think you could get what you want by creating a List<Dot> public property in your line class. Then you could add matching dots that way to track them.
You will need a collection type as the dictionary class does not support multiple values for the same key.
So you can for example use Dictionary<Line, List<Dot>>.
To add dots, you will then need to create a list per line the first time you want to access it:
if(!TempDotsInLines.TryGetValue(line, out List<Dot> dotList))
TempDotsInLines[line] = dotList = new List<Dot>();
dotList.Add(dot);

Deleting a specific item of an array [duplicate]

This question already has answers here:
Remove element of a regular array
(15 answers)
Closed 9 years ago.
string[] columns
I want to delete the item on an index specified by a variable of type int.
How do I do this ?
I tried
columns.RemoveAt(MY_INT_HERE);
But apparently this does not works.
Array is immutable class, you can't change it, all you can do is to re-create it:
List<String> list = columns.ToList(); // <- to List which is mutable
list.RemoveAt(MY_INT_HERE); // <- remove
string[] columns = list.ToArray(); // <- back to array
May be the best solution is to redesign your code: change immutable array into List<String>:
List<String> columns = ...
columns.RemoveAt(MY_INT_HERE);
If you don't want to use linq you can use this function :
public string[] RemoveAt(string[] stringArray, int index)
{
if (index < 0 || index >= stringArray.Length)
return stringArray;
var newArray = new string[stringArray.Length - 1];
int j = 0;
for (int i = 0; i < stringArray.Length; i++)
{
if(i == index)continue;
newArray[j] = stringArray[i];
j++;
}
return newArray;
}
You use it like that : columns = RemoveAt(columns, MY_INT_HERE)
You can also make it to an extension method.
You cannot delete items in an array, because the length of a C# array is fixed at the time when it is created, and cannot be changed after that.
You can null out the corresponding element to get rid of the string, or use LINQ to produce a new array, like this:
columns = columns.Take(MY_INT_HERE-1).Concat(columns.Skip(MY_INT_HERE)).ToArray();
You need to add using System.Linq at the top of your C# file in order for this to compile.
However, using a List<string> would be a better solution:
List<string> columns;
columns.RemoveAt(MY_INT_HERE);
Try one of the following (depending on what you need):
columns[MY_INT_HERE] = null;
columns[MY_INT_HERE] = string.Empty;
...otherwise you'll just have to create a new array which has a length of 1 less than your current array, and copy the values over.
If you want something more flexible, you might use a something like a List<string>, where you can use RemoveAt()
Arrays are faster for the computer to work with but slower for a programmer. You will have to find that value with a loop or some other means, then set that position to null. You will end up with an empty space in the array. You could reallocate the array etc etc...
What is easier to use for relatively small amounts of data is a List. You can do myList.RemoveAt(100); and it will work nicely.
You can not delete it.You can recreate the array or I advice you to use List<string> for the same.
List<string> columns = new List<string>();
columns.RemoveAt(1);
It will remove the 2nd element from your List<String> columns

Displaying strings from Array without repeats

I working on a project in c# asp.net. I would like to randomly display a string from either an array or list, if certain conditions are met, I would like to display another random string that has not been displayed.
EX.
LIST<string> myString = new List<string> {"one", "two", "three", "four", "five"};
or
string[] myString = new[] {"one", "two", "three", "four", "five"};
void btnAnswer_Click(Object sender, EventArgs e)
{
string Next = myString[random.Next(myString.Length)];
if(my condition is met)
{
lbl.Text = Next;
}
}
I can randomly call a string from my list or array, but not sure how to store repeat results. I've tried using an algorithm that jumbles the array and then a counter for the index, but the counter (counter++) seems to add 1 once and then stops. I've tried using a list and removing the string I use, but it seems to repeat after all strings have been used.
If more code is needed I can provide, just need a point in the right direction.
One option is to display one of the random string and store it in a ViewState.
When you come next time again, check whether new random string is already there in ViewState or not. If it is there in ViewState then get another random string.
Couple of options:
Have an array or list which is a copy of the master array, and whenever you choose one, remove it from the array. Once the array is empty, refresh it from the master array.
Similar, just create your array, shuffle it, and start giving out strings by order. so array[0], next would be array[1], and so on, once you reach the end, shuffle and start again.
There are probably others as well :)
Edit:
If I understand correctly from the comments, you are talking about the option where the input is not unique to begin with. If that is the case, you can create your list with a simple linq query to get only unique values (using distinct), guaranteeing no duplicates.
Have a look at this question for an example.
You can copy the indices into a list, it will save memory while allow us to track all the remaining items:
var indices = Enumerable.Range(0,myString.Count).ToList();
//define some method to get next index
public int? NextIndex(){
if(indices.Count == 0) return null;
int i = random.Next(indices.Count);
int k = indices[i];
indices.RemoveAt(i);
return k;
}
if(my condition is met) {
int? nextIndex = NextIndex();
lbl.Text = nextIndex == null ? "" : myString[nextIndex.Value];
}
Note that the Text is set to empty if there won't be no more remaining string, however you can handle that case yourself in another way such as keep the text unchanged.
You could probably do that, but why not get a unique list of strings first?
var uniqueStrings = myString.Distinct().ToList();
Then as you select strings, do a .Remove() on the last randomly selected value from uniqueStrings.
You said that:
I've tried using a list and removing the string I use, but it seems to repeat after all strings have been used.
The problem here is using the same instance of random for your series after you've run out. If you re-instantiate random = new Random(), the variable is re-seeded and you will have totally different results from what was generated before.

Check if Characters in ArrayList C# exist - C# (2.0)

I was wondering if there is a way in an ArrayList that I can search to see if the record contains a certain characters, If so then grab the whole entire sentence and put in into a string. For Example:
list[0] = "C:\Test3\One_Title_Here.pdf";
list[1] = "D:\Two_Here.pdf";
list[2] = "C:\Test\Hmmm_Joke.pdf";
list[3] = "C:\Test2\Testing.pdf";
Looking for: "Hmmm_Joke.pdf"
Want to get: "C:\Test\Hmmm_Joke.pdf" and put it in the Remove()
protected void RemoveOther(ArrayList list, string Field)
{
string removeStr;
-- Put code in here to search for part of a string which is Field --
-- Grab that string here and put it into a new variable --
list.Contains();
list.Remove(removeStr);
}
Hope this makes sense. Thanks.
Loop through each string in the array list and if the string does not contain the search term then add it to new list, like this:
string searchString = "Hmmm_Joke.pdf";
ArrayList newList = new ArrayList();
foreach(string item in list)
{
if(!item.ToLower().Contains(searchString.ToLower()))
{
newList.Add(item);
}
}
Now you can work with the new list that has excluded any matches of the search string value.
Note: Made string be lowercase for comparison to avoid casing issues.
In order to remove a value from your ArrayList you'll need to loop through the values and check each one to see if it contains the desired value. Keep track of that index, or indexes if there are many.
Then after you have found all of the values you wish to remove, you can call ArrayList.RemoveAt to remove the values you want. If you are removing multiple values, start with the largest index and then process the smaller indexes, otherwise, the indexes will be off if you remove the smallest first.
This will do the job without raising an InvalidOperationException:
string searchString = "Hmmm_Joke.pdf";
foreach (string item in list.ToArray())
{
if (item.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
{
list.Remove(item);
}
}
I also made it case insensitive.
Good luck with your task.
I would rather use LINQ to solve this. Since IEnumerables are immutable, we should first get what we want removed and then, remove it.
var toDelete = Array.FindAll(list.ToArray(), s =>
s.ToString().IndexOf("Hmmm_Joke.pdf", StringComparison.OrdinalIgnoreCase) >= 0
).ToList();
toDelete.ForEach(item => list.Remove(item));
Of course, use a variable where is hardcoded.
I would also recommend read this question: Case insensitive 'Contains(string)'
It discuss the proper way to work with characters, since convert to Upper case/Lower case since it costs a lot of performance and may result in unexpected behaviours when dealing with file names like: 文書.pdf

Confusion in using Arrays in C#

is it possible to accept more than one entires,as variables, and then change it to an array! as for example, the user would enter more than one name, but not defined how many names they should enter, and when I received the names I would change it to an array, is that possible ?
Thanks!
In .NET arrays have fixed length. If you want to be able to dynamically add elements to a list you could use the List<T> class.
For example:
List<string> names = new List<string>();
Now you could start adding elements to the list:
names.Add("foo");
names.Add("bar");
names.Add("baz");
And you could also get the corresponding fixed length array using the ToArray() method:
string[] namesArray = names.ToArray();
I think what you're looking for is the param object []. It's used for an undetermined number or parameters into a function. Your function would go like this:
public static void SayHello(params string[] names){
foreach(var name in names){
Console.WriteLine("Hello " + name);
}
}
And you could call it like this:
SayHello("Bob", "Bill", "Susan");
SayHello("Jenny");
If the user is going to enter more than one name, then I suggest you create a list of strings instead of an array.

Categories

Resources