I want to remove the element form the array. Actually I don't know the the index of the element and want to remove through it's value. I have tried a lot but fail. This is the function which i used to add element in the Array
string [] Arr;
int i = 0;
public void AddTOList(string ItemName)
{
Arr[i] = ItemName;
i++;
}
And I want to remove the element by the value. I know the below function is wrong but I want to explain what I want:
public void RemoveFromList(string ItemName)
{
A["Some_String"] = null;
}
Thanks
If you want to remove items by a string key then use a Dictionary
var d = new Dictionary<string, int>();
d.Add("Key1", 3);
int t = d["Key1"];
Or something like that.
Array has a fixed size, which is not suitable for your requirement. Instead you can use List<string>.
List<string> myList = new List<string>();
//add an item
myList.Add("hi");
//remove an item by its value
myList.Remove("hi");
List<string> list = new List<string>(A);
list.Remove(ItemName);
A = list.ToArray();
and #see Array.Resize
and #see Array.IndexOf
You can iterate through every value in array and if found then remove it. Something like this
string[] arr = new string[] { "apple", "ball", "cat", "dog", "elephant", "fan", "goat", "hat" };
string itemToRemove = "fan";
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == itemToRemove)
{
arr[i]=null;
break;
}
}
Related
I want to implement 'string[] loadedText' into 'string[] dataList', but I keep getting an error saying "Cannot implicitly convert type 'string[]' to 'string'".
string[] dataList = new string[1800];
StreamReader loadNewData = new StreamReader("podaciB.txt");
int i = 0;
while (i < 1800)
{
string[] loadedData = loadNewData.ReadLine().Split(';');
dataList[i] = loadedData;
i++;
}
I need the 'dataList' array that will contain 1800 'loadedData' arrays which contain 4 strings in them.
What you need is a jagged array:
string[][] dataList = new string[1800][];
loadNewData.ReadLine().Split(';'); returns array of string and you are storing array of strings into dataList[i] i.e. string element of string array. This is the reason behind error which you mentioned in your question
If you want to store loadNewData.ReadLine().Split(';'); into an array then I would suggest you to use nested list List<List<string>>
Something like,
List<List<string>> dataList = List<List<string>>();
StreamReader loadNewData = new StreamReader("podaciB.txt");
int i = 0;
while (i < 1800)
{
var innerList = loadNewData.ReadLine().Split(';').ToList();
dataList.Add(innerList);
i++;
}
It seems you need an array of array of strings, something like string[][].
You can do it like this:
string[][] dataList = new string[1800][];
StreamReader loadNewData = new StreamReader("podaciB.txt");
int i = 0;
while (i < 1800)
{
string[] loadedData = loadNewData.ReadLine().Split(';');
dataList[i] = loadedData;
i++;
}
As you are splitting loadedNewData, you receive string[] already, because Split() function returns string[].
Variable.cs
public string[] CcEmails { get; set; }
Mail.cs
EDTO.CcEmails = dr["rsh_ccmail"].ToString().Split(';');
here i got two strings eg. xxxx#gmail.com ; yyy#gmail.com
MailProcess.cs
dataRPT1=get data from sql
EDTO.CcEmails = new string[dataRPT1.Rows.Count];
for (int i = 0; i < dataRPT1.Rows.Count; i++)
{
EDTO.CcEmails[i] = dataRPT1.Rows[i]["email_addr"].ToString();
}
Here i got list of string eg.aaa#gmail.com ......
I am try to add with existing but it add only new values..Anyone could help me..
I tend to use union, although that will remove duplicate entries. But to keep all entries you can use Concat on the array.
var emailString = "me#test.com;you#test.com";
string[] emails = emailString.Split(';');
string[] emailsFromSQL = new string[3];
emailsFromSQL[0] = "everyone#test.com";
emailsFromSQL[1] = "everyone2#test.com";
emailsFromSQL[2] = "everyone2#test.com";
//No Duplicates
var combined = emails.Union(emailsFromSQL).ToArray();
//Duplicates
var allCombined = emails.Concat(emailsFromSQL).ToArray();
Thanks
I find the easiest way of doing this is to create a list, add items to the list, then use string.Join to create the new string.
var items = new List<string>();
for (int i = 0; i < dataRPT1.Rows.Count; i++)
{
items.Add(dataRPT1.Rows[i]["email_addr"].ToString());
}
EDTO.CcEmails = string.Join(";", items);
Update after changed question:
If the type of the CcEmails is an array, the last line could be:
EDTO.CcEmails = items.ToArray();
I have an array of strings and want to output those that are of a certain length from the array.
string[]myArray = {"stringone", "stringtwo", "stringthree"};
I have tried doing
foreach(thing in myArray){
if(thing.length<10){
do stuff
}
#output
But doesnt work. Where am i going wrong?
I'm using C# in asp.net.
Many thanks.
you need to specify that thing is a string or var.
Also, you need to capitalize Length.
public void McTester()
{
string[] myArray = { "stringone", "stringtwo", "stringthree" };
foreach (string thing in myArray)
{
if (thing.Length < 10)
{
//do stuff
}
}
}
string[] myArray = { "stringone", "stringtwo", "stringthree" };
var lessThan10Length = myArray.Where(x=> x.Length < 10).ToList();
Assuming your problem was length instead of Length, you can filter out only the values you need using a Where clause:
string[] myArray = { "stringone", "stringtwo", "stringthree" };
foreach (string thing in myArray.Where(thing => thing.Length < 10))
{
// Here you'll only iterate values
// whos length is less than 10
}
So what I am trying do is retrieve the index of the first item, in the list, that begins with "whatever", I am not sure how to do this.
My attempt (lol):
List<string> txtLines = new List<string>();
//Fill a List<string> with the lines from the txt file.
foreach(string str in File.ReadAllLines(fileName)) {
txtLines.Add(str);
}
//Insert the line you want to add last under the tag 'item1'.
int index = 1;
index = txtLines.IndexOf(npcID);
Yea I know it isn't really anything, and it is wrong because it seems to be looking for an item that is equal to npcID rather than the line that begins with it.
If you want "StartsWith" you can use FindIndex
int index = txtLines.FindIndex(x => x.StartsWith("whatever"));
if your txtLines is a List Type, you need to put it in a loop, after that retrieve the value
int index = 1;
foreach(string line in txtLines) {
if(line.StartsWith(npcID)) { break; }
index ++;
}
Suppose txtLines was filled, now :
List<int> index = new List<int>();
for (int i = 0; i < txtLines.Count(); i++)
{
index.Add(i);
}
now you have a list of int contain index of all txtLines elements. you can call first element of List<int> index by this code : index.First();
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Delete row of 2D string array in C#
i have a 2d string array, I want to delete a specified row from the array.
string[] a = new string[] { "a", "b" }; //dummy string array
int deleteIndex = 1; //we want to "delete" element in position 1 of string
a = a.ToList().Where(i => !a.ElementAt(deleteIndex).Equals(i)).ToArray();
dirty but gives the expected result (foreach through the array to test it)
EDIT missed the "2d array" detail, here is the right code for the job
string[][] a = new string[][] {
new string[] { "a", "b" } /*1st row*/,
new string[] { "c", "d" } /*2nd row*/,
new string[] { "e", "f" } /*3rd row*/
};
int rowToRemove = 1; //we want to get rid of row {"c","d"}
//a = a.ToList().Where(i => !i.Equals(a.ElementAt(rowToRemove))).ToArray(); //a now has 2 rows, 1st and 3rd only.
a = a.Where((el, i) => i != rowToRemove).ToArray(); // even better way to do it maybe
code updated
As has been said above you cant remove from an array.
If you are going to need to remove rows quite often maybe change from using a 2d array to a list containing an array of string. This way you can make use of the remove methods that list implements.
Ok so I said you can't "delete" them. That's still true. You'll have to create a new array instance with enough space for the items you want to keep and copy them over.
If this is a jagged array, using LINQ here could simplify this.
string[][] arr2d =
{
new[] { "foo" },
new[] { "bar", "baz" },
new[] { "qux" },
};
// to remove the second row (index 1)
int rowToRemove = 1;
string[][] newArr2d = arr2d
.Where((arr, index) => index != rowToRemove)
.ToArray();
// to remove multiple rows (by index)
HashSet<int> rowsToRemove = new HashSet<int> { 0, 2 };
string[][] newArr2d = arr2d
.Where((arr, index) => !rowsToRemove.Contains(index))
.ToArray();
You could use other LINQ methods to remove ranges of rows easier (e.g., Skip(), Take(), TakeWhile(), etc.).
If this is a true two-dimensional (or other multi-dimensional) array, you won't be able to use LINQ here and will have to do it by hand and it gets more involved. This still applies to the jagged array as well.
string[,] arr2d =
{
{ "foo", null },
{ "bar", "baz" },
{ "qux", null },
};
// to remove the second row (index 1)
int rowToRemove = 1;
int rowsToKeep = arr2d.GetLength(0) - 1;
string[,] newArr2d = new string[rowsToKeep, arr2d.GetLength(1)];
int currentRow = 0;
for (int i = 0; i < arr2d.GetLength(0); i++)
{
if (i != rowToRemove)
{
for (int j = 0; j < arr2d.GetLength(1); j++)
{
newArr2d[currentRow, j] = arr2d[i, j];
}
currentRow++;
}
}
// to remove multiple rows (by index)
HashSet<int> rowsToRemove = new HashSet<int> { 0, 2 };
int rowsToKeep = arr2d.GetLength(0) - rowsToRemove.Count;
string[,] newArr2d = new string[rowsToKeep, arr2d.GetLength(1)];
int currentRow = 0;
for (int i = 0; i < arr2d.GetLength(0); i++)
{
if (!rowsToRemove.Contains(i))
{
for (int j = 0; j < arr2d.GetLength(1); j++)
{
newArr2d[currentRow, j] = arr2d[i, j];
}
currentRow++;
}
}
Instead of array you can use List or ArrayList class. Using it you can dynamically add element and remove based on your requirement. Array is fixed in size, which can not be manipulated dynamically.
The best way is to work with a List<Type>! The items are ordered in the way the are added to the list and each of them can be deleted.
Like this:
var items = new List<string>;
items.Add("One");
items.Add("Two");
items.RemoveAt(1);