Add item in list in specific position - c#

I'm trying to find if i can add an item in list in specific position.
Example
string[] tokens= new string[10];
tokens[5]="TestString";
when i'm trying this to list
List<string> mitems = new List<string>();
mitems.Insert(5, "TestString");
I'm getting error list inside a list index out of range.
Is there any relative to this for a list?

Use the Insert(index, item); method.
Have a look at MSDN Insert for more information.
But you will get an error when you're trying to insert an item at an index which is not existing.
You could init your list with 10 empty values like you did with your array but if you use Insert a new entry is created and not an old replaced like with a dictionary. That would mean you would have 11 entries after the first use of Insert
This example code
var items = new List<string>();
items.AddRange(Enumerable.Repeat(string.Empty, 10));
Console.WriteLine(items.Count);
items.Insert(5, "TestString");
Console.WriteLine(items.Count);
gives this output (for better understanding):
10
11

private static void Myfunc()
{
List<string> l = new List<string>();
string opt = "y";
while (opt == "y")
{
Console.WriteLine("Do you want to add in a specific position? (y/n)");
string pos = Console.ReadLine();
if (pos == "y")
{
Console.WriteLine("Which index you want to add?");
int index = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Add items in {0}", index);
l.Insert(index, Console.ReadLine());
}
else
{
Console.WriteLine("Enter to add in a list");
l.Add(Console.ReadLine());
Console.WriteLine("Do you wish to continue? (y/n)");
opt = Console.ReadLine();
}
Console.WriteLine("Do you want to print the list? (y/n)");
string print = Console.ReadLine();
if (print == "y")
{
foreach (var item in l)
{
Console.WriteLine(item);
}
}
}
I wrote this function for you.
Add this function to a console app for better understanding how list works for insert and append
EDIT 1:
I just saw your edit, another way of initializing a list with default values and then insert something in a certain position would be by initializing the list like this :-
List<string> l = Enumerable.Repeat("something blank", 10).ToList();
And then add to an index of your choice

Following adds default values of string at every index from 0-9
string[] tokens= new string[10];
But list is created on heap nothing instantiated. No default assigned values.
List<string> mitems = new List<string>();
If you try following it will fail as there are no values at 0-5
mitems.Insert(5, "TestString");
If you do following it will work
mitems.Insert(0, "TestString");

You can use List<T>.Insert(int, T) method to do that, example:
var tokens = new List<string>();
for (int i = 0; i < 10; i++)
tokens.Add(string.Empty);
tokens.Insert(5, "TestString");
See MSDN
Edit:
If you were just trying to replace the item in index of 5, than the [] will also do the trick as following example:
var tokens = new List<string>(10);
for (int i = 0; i < 10; i++)
tokens.Add(string.Empty);
tokens[5] = "TestString";

Related

How can I split a string to store contents in two different arrays in c#?

The string I want to split is an array of strings.
the array contains strings like:
G1,Active
G2,Inactive
G3,Inactive
.
.
G24,Active
Now I want to store the G's in an array, and Active or Inactive in a different array. So far I have tried this which has successfully store all the G's part but I have lost the other part. I used Split fucntion but did not work so I have tried this.
int i = 0;
for(i = 0; i <= grids.Length; i++)
{
string temp = grids[i];
temp = temp.Replace(",", " ");
if (temp.Contains(' '))
{
int index = temp.IndexOf(' ');
grids[i] = temp.Substring(0, index);
}
//System.Console.WriteLine(temp);
}
Please help me how to achieve this goal. I am new to C#.
If I understand the problem correctly - we have an array of strings Eg:
arrayOfStrings[24] =
{
"G1,Active",
"G2,Inactive",
"G3,Active",
...
"G24,Active"
}
Now we want to split each item and store the g part in one array and the status into another.
Working with arrays the solution is to - traverse the arrayOfStrings.
Per each item in the arrayOfStrings we split it by ',' separator.
The Split operation will return another array of two elements the g part and the status - which will be stored respectively into distinct arrays (gArray and statusArray) for later retrieval. Those arrays will have a 1-to-1 relation.
Here is my implementation:
static string[] LoadArray()
{
return new string[]
{
"G1,Active",
"G2,Inactive",
"G3,Active",
"G4,Active",
"G5,Active",
"G6,Inactive",
"G7,Active",
"G8,Active",
"G9,Active",
"G10,Active",
"G11,Inactive",
"G12,Active",
"G13,Active",
"G14,Inactive",
"G15,Active",
"G16,Inactive",
"G17,Active",
"G18,Active",
"G19,Inactive",
"G20,Active",
"G21,Inactive",
"G22,Active",
"G23,Inactive",
"G24,Active"
};
}
static void Main(string[] args)
{
string[] myarrayOfStrings = LoadArray();
string[] gArray = new string[24];
string[] statusArray = new string[24];
int index = 0;
foreach (var item in myarrayOfStrings)
{
var arraySplit = item.Split(',');
gArray[index] = arraySplit[0];
statusArray[index] = arraySplit[1];
index++;
}
for (int i = 0; i < gArray.Length; i++)
{
Console.WriteLine("{0} has status : {1}", gArray[i] , statusArray[i]);
}
Console.ReadLine();
}
seems like you have a list of Gxx,Active my recomendation is first of all you split the string based on the space, which will give you the array previoulsy mentioned doing the next:
string text = "G1,Active G2,Inactive G3,Inactive G24,Active";
string[] splitedGItems = text.Split(" ");
So, now you have an array, and I strongly recommend you to use an object/Tuple/Dictionary depends of what suits you more in the entire scenario. for now i will use Dictionary as it seems to be key-value
Dictionary<string, string> GxListActiveInactive = new Dictionary<string, string>();
foreach(var singleGItems in splitedGItems)
{
string[] definition = singleGItems.Split(",");
GxListActiveInactive.Add(definition[0], definition[1]);
}
What im achiving in this code is create a collection which is key-value, now you have to search the G24 manually doing the next
string G24Value = GxListActiveInactive.FirstOrDefault(a => a.Key == "G24").Value;
just do it :
var splitedArray = YourStringArray.ToDictionary(x=>x.Split(',')[0],x=>x.Split(',')[1]);
var gArray = splitedArray.Keys;
var activeInactiveArray = splitedArray.Values;
I hope it will be useful
You can divide the string using Split; the first part should be the G's, while the second part will be "Active" or "Inactive".
int i;
string[] temp, activity = new string[grids.Length];
for(i = 0; i <= grids.Length; i++)
{
temp = grids[i].Split(',');
grids[i] = temp[0];
activity[i] = temp[1];
}

How to get an index of a word in string array

I want to get the index of a word in a string array.
for example, the sentence I will input is 'I love you.'
I have words[1] = love, how can I get the position of 'love' is 1? I could do it but just inside the if state. I want to bring it outside. Please help me.
This is my code.
static void Main(string[] args)
{
Console.WriteLine("sentence: ");
string a = Console.ReadLine();
String[] words = a.Split(' ');
List<string> verbs = new List<string>();
verbs.Add("love");
int i = 0;
while (i < words.Length) {
foreach (string verb in verbs) {
if (words[i] == verb) {
int index = i;
Console.WriteLine(i);
}
} i++;
}
Console.ReadKey();
}
I could do it but just inside the if state. I want to bring it outside.
Your code identifies the index correctly, all you need to do now is storing it for use outside the loop.
Make a list of ints, and call Add on it for the matches that you identify:
var indexes = new List<int>();
while (i < words.Length) {
foreach (string verb in verbs) {
if (words[i] == verb) {
int index = i;
indexes.Add(i);
break;
}
}
i++;
}
You can replace the inner loop with a call of Contains method, and the outer loop with a for:
for (var i = 0 ; i != words.Length ; i++) {
if (verbs.Contains(words[i])) {
indexes.Add(i);
}
}
Finally, the whole sequence can be converted to a single LINQ query:
var indexes = words
.Select((w,i) => new {w,i})
.Where(p => verbs.Contains(p.w))
.Select(p => p.i)
.ToList();
Here is an example
var a = "I love you.";
var words = a.Split(' ');
var index = Array.IndexOf(words,"love");
Console.WriteLine(index);
private int GetWordIndex(string WordOrigin, string GetWord)
{
string[] words = WordOrigin.Split(' ');
int Index = Array.IndexOf(words, GetWord);
return Index;
}
assuming that you called the function as GetWordIndex("Hello C# World", "C#");, WordOrigin is Hello C# World and GetWord is C#
now according to the function:
string[] words = WordsOrigin.Split(' '); broke the string literal into an array of strings where the words would be split for every spaces in between them. so Hello C# World would then be broken down into Hello, C#, and World.
int Index = Array.IndexOf(words, GetWord); gets the Index of whatever GetWord is, according to the sample i provided, we are looking for the word C# from Hello C# World that is then splitted into an Array of String
return Index; simply returns whatever index it was located from

Add to array list from another array list

I have a program where I am trying to move items from one arraylist to another via a listbox but when I try to add it to the the second arraylist it does not add there.
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
list1.Add(new Class(var1, var2, var3, var4, var5, var6, var7));
foreach (object o in list1)
{
class m = (class)o;
selectionBox.Items.Add(m);
}
I initialised everything above and added everything to the class and then to the listbox. Note the vars I have got from an XML file.
bool req = true;
if (selectionBox.SelectedItem != null)
{
Count++;
errorLabel.Text = "";
for (int i = 0; i < selectionBox.Items.Count; i++)
{
if (selectionBox.GetSelected(i) == true)
{
class m = selectionBox.SelectedItem as class;
if (m.var2 == ((Modules)selectionBox.Items[i]).var2)
{
list2.Add(list1.IndexOf(i));
}
}
}
}
else
{
errorLabel.Text = "Error";
}
Here I am trying to add it to the second array list but it does not work the if statement however is correct I have tried this with print statements. So can someone tell me why the following line does not add to the list?
list2.Add(list1.IndexOf(i));
list2.Add(list1.IndexOf(i)); will give you the index (position) of each element. Not the element itself.
To add the element you would need to do something like this:
list2.Add(list1[i]);
Also, just as an aside, this will only copy the reference to each element, it will not create a new copy of each.

Need to add each number 0-x to end of line?

I'm making an app and I'm almost done. I just need to know how I can streamread a txt list and foreach line, add numbers 0-x (x will be the number the user puts in the textbox) and add it to a list. So basically, it would be like this
You import a list with 'dog' on one line, 'cat' on another, and 'fish' on the third. You type '5' into the textbox. the app puts all this into a list:
dog1
dog2
dog3
dog4
dog5
cat1
cat2
cat3
cat4
cat5
fish1
fish2
fish3
fish4
fish5
thanks!
The code below should work for you. I assume you can acquire the count value on your own.
var animals = File.ReadAllLines("yourFile.txt"); //new[] {"dog", "cat", "fish"};
var count = 5;
var merged =
from a in animals
from n in Enumerable.Range(1, count)
select a + n;
foreach (var m in merged)
Console.WriteLine(m); //act on each however you want
You can read a text file with File.ReadAllLines. This gives you an array you can iterate over with foreach.
In this foreach loop you can perform another loop from 1 to the number the user entered. int.Parse comes in handy for converting the string the user entered into a number C# can do something with. For the actual iteration you can use a for loop.
You can then add each item to a list.
There is a good example for reading each line in a filestream here: http://msdn.microsoft.com/en-us/library/e4y2dch9.aspx
private List<string> GetThings(string fileName, int count)
{
string[] lines = File.ReadAllLines(fileName);
List<string> result = new List<string>();
foreach (string item in lines)
{
for (int i = 1; i <= count; i++)
result.Add(item + i.ToString());
}
return result;
}
string[] inputList = File.ReadAllLines("yourFile.txt");
List<String> listOfThings = new List<String>();
foreach (string i in inputList)
{
for (int k = 0; k < 5; k++)
{
listOfThings.Add(i + " " + k.ToString());
}
}
then after that, you can print out the list like this:
foreach (string outp in listOfThings)
{
Console.WriteLine(outp);
}
output:
some value 0
some value 1
some value 2
some value 3
some value 4
some other value 0
some other value 1
some other value 2
some other value 3
some other value 4

Exception during iteration on collection and remove items from that collection [duplicate]

This question already has answers here:
What is the best way to modify a list in a 'foreach' loop?
(11 answers)
Closed 9 years ago.
I remove item from ArrayList in foreach loop and get follwing exception.
Collection was modified; enumeration operation may not execute.
How can I remove items in foreach,
EDIT: There might be one item to remove or two or all.
Following is my code:
/*
* Need to remove all items from 'attachementsFielPath' which does not exist in names array.
*/
try
{
string attachmentFileNames = txtAttachment.Text.Trim(); // Textbox having file names.
string[] names = attachmentFileNames.Split(new char[] { ';' });
int index = 0;
// attachmentsFilePath is ArrayList holding full path of fiels user selected at any time.
foreach (var fullFilePath in attachmentsFilePath)
{
bool isNeedToRemove = true;
// Extract filename from full path.
string fileName = fullFilePath.ToString().Substring(fullFilePath.ToString().LastIndexOf('\\') + 1);
for (int i = 0; i < names.Length; i++)
{
// If filename found in array then no need to check remaining items.
if (fileName.Equals(names[i].Trim()))
{
isNeedToRemove = false;
break;
}
}
// If file not found in names array, remove it.
if (isNeedToRemove)
{
attachmentsFilePath.RemoveAt(index);
isNeedToRemove = true;
}
index++;
}
}
catch (Exception ex)
{
throw ex;
}
EDIT: Can you also advice on code. Do I need to break it into small methods and exception handling etc.
Invalid argument exception On creating generic list from ArrayList
foreach (var fullFilePath in new List<string>(attachmentsFilePath))
{
When I use List<ArrayList> the exception is
Argument '1': cannot convert from 'System.Collections.ArrayList' to 'int'
attachmentsFilePath is declared like this
ArrayList attachmentsFilePath = new ArrayList();
But when I declared it like this, problem solved
List<ArrayList> attachmentsFilePath = new List<ArrayList>();
Another way of doing it, start from the end and delete the ones you want:
List<int> numbers = new int[] { 1, 2, 3, 4, 5, 6 }.ToList();
for (int i = numbers.Count - 1; i >= 0; i--)
{
numbers.RemoveAt(i);
}
You can't remove an item from a collection while iterating over it.
You can find the index of the item that needs to be removed and remove it after iteration has finished.
int indexToRemove = 0;
// Iteration start
if (fileName.Equals(names[i].Trim()))
{
indexToRemove = i;
break;
}
// End of iteration
attachmentsFilePath.RemoveAt(indexToRemove);
If, however, you need to remove more than one item, iterate over a copy of the list:
foreach(string fullFilePath in new List<string>(attachmentsFilePath))
{
// check and remove from _original_ list
}
You can iterate over a copy of the collection:
foreach(var fullFilePath in new ArrayList(attachmentsFilePath))
{
// do stuff
}
List<string> names = new List<string>() { "Jon", "Eric", "Me", "AnotherOne" };
List<string> list = new List<string>() { "Person1", "Paerson2","Eric"};
list.RemoveAll(x => !names.Any(y => y == x));
list.ForEach(Console.WriteLine);
while enumerating (or using foreach) you cannot modify that collection. If you really want to remove items, then you can mark them and later remove them from list using its Remove method
do the following:
foreach (var fullFilePath in new List(attachmentsFilePath))
{
this way you create a copy of the original list to iterate through
You could loop over the collection to see which items need to be delete and store those indexes in a separate collection. Finally you would need to loop over the indexes to be deleted in reverse order and remove each from the original collection.
list<int> itemsToDelete
for(int i = 0; i < items.Count; i++)
{
if(shouldBeDeleted(items[i]))
{
itemsToDelete.Add(i);
}
}
foreach(int index in itemsToDelete.Reverse())
{
items.RemoveAt(i);
}

Categories