Add value to array in C# - c#

Hello I'm just starting in c # and am practicing with arrays, my question is how I can add a name called "steve" the array of this code:
string[] names = new string[] {"Matt", "Joanne", "Robert"};
foreach (string i in names)
{
richTextBox1.AppendText(i + Environment.NewLine);
}
anyone can help me?

You can resize an array, however its probably better to just use a list if you need a collection who's size changes.
Note that resizing an array actually just creates a new array of the size you want behind the scenes and copies over all the data

Arrays don't play well with this idea. Usually, people use List for this kind of thing.
List<string> names = new List<string> {"Matt", "Joanne", "Robert"};
names.Add("Steve");
foreach (string i in names)
{
richTextBox1.AppendText(i + Environment.NewLine);
}

You can't add elements to an array once the array has been created. You can:
Add the element before the array has been created as a literal:
string[] names = new string[] {"Matt", "Joanne", "Robert", "Steve", "Another name", "Tons of other names"};
Or you can use a collection that allows you to add elements after it has been created such as a List. To use a List instead of array, make sure you have the following directive using System.Collections.Generic at the top of your main file (should be included by default). Now you can do:
List<string> names = new List<string> {"Matt", "Joanne", "Robert"};
names.Add("Steve");
names.Add("Another one");

Although you can expand .NET arrays, in a situation like this you would be better off with a List<string>:
List<string> names = new List<string> {"Matt", "Joanne", "Robert"};
Now you can add a new name to names by calling Add:
names.Add("Steve");
Note: rather than using AppendText in a loop, you could use string.Join, like this:
richTextBox1.AppendText(names.Join(Environment.NewLine, names));

To add the Item to the array, using the code you provided, you can do this:
string[] names = new string[] { "Matt", "Joanne", "Robert" };
Array.Resize(ref names, names.Length + 1);
names[names.Length - 1] = "Steve";
foreach (string i in names)
{
richTextBox1.AppendText(i + Environment.NewLine);
}
Consider using this code instead, that uses List:
List<string> names = new List<string> { "Matt", "Joanne", "Robert" };
names.Add("Steve"); // Add a new entry
richTextBox1.AppendText(String.Join(Environment.NewLine, names));

The array has a fix size. At first you've created that with three elements, so it will have three elements. You can modify any element so:
names[index] = "value";

You can make a list from an Array by writting:
List<string> list = names.OfType<string>().ToList();
and then continue from there as the others mentioned!

Example for resizing your array:
string[] names = { "Matt", "Joanne", "Robert" };
Array.Resize(ref names, names.Length + 1);
names[names.Length - 1] = "Steve";
Steve has given the proper reference above.

Related

How can I only store the second part of a string in a list?

I have a list Textlist1 that contains only strings. Each item in the list begins with the same text: "sentence.text.", but I only want to store the second part of the string in another list, I don't want to store the first part "sentence.text." in the list Textlist2.
For example:
List<string> Textlist1 = new List<string>();
List<string> Textlist2 = new List<string>();
The full strings are stored in Textlist1.
Textlist1[0] = "sentence.text.My name is Fred"
Textlist1[1] = "sentence.text.Jenny is my sister"
How can I only add "My name is Fred" and "Jenny is my sister" to Textlist2?
The result should be like this:
Textlist2[0] = "My name is Fred"
Textlist2[1] = "Jenny is my sister"
See online result: https://dotnetfiddle.net/MpswLZ
List<string> Textlist1 = new List<string>() {
"sentence.text.My name is Fred",
"sentence.text.Jenny is my sister"
};
List<string> Textlist2 = new List<string>();
Textlist2 = Textlist1.Select(item => item.Split('.')[2]).ToList();
You can use Linq. (You need do add using System.Linq)
Textlist2= Textlist1
.Select(i=> i.Substring("sentence.text.".Length))
.ToList();
Split the input strings by the periods, limiting the split to 3. Then take the last entry from the array that split produces.
Textlist2[0] = Textlist1[0].Split('.', 3)[2];
Textlist2[1] = Textlist1[1].Split('.', 3)[2];
You could use Regex.Replace the text.
var regex = new Regex("^sentence.text.",RegexOptions.Compiled);
Textlist2.AddRange(Textlist1.Select(x=>regex.Replace(x,string.Empty)));
The "^" in Regex ensure the required text ("sentence.text") is matched only at the beginning of string and not else where.
Sample Input
Sample Output
List<string> Textlist1 = new List<string>
{
"sentence.text.a",
"sentence.text.b"
};
string prefix = "sentence.text.";
List<string> Textlist2 = Textlist1.Select(x => x.Substring(prefix.Length)).ToList();
https://dotnetfiddle.net/oFhvfs
There are ultimately many ways of doing this, this is just one solution. Which approach you choose depends on how complex the pattern replacement is. I've gone with a simplistic approach as your example is a very simple case.

Create nested list (array) of strings from list of strings

I have a list of names. From these, I want to create a new list of lists (or jagged array, if that works better), where the lower-level lists contain variations of the names.
The basic idea is that you take a name and remove one letter at a time to create a list which features all of these creations, plus the original name. So for example, if your names are "bob" and "alice", I want to output
[["bo", "bb","ob","bob"], ["alic", "alie", "alce", "aice", "lice", "alice"]].
I can easily do this for just one name, but I run into problems I can't resolve when I try to create such a nested list (I'm relatively new to C#). Here's a toy example of what I've been trying:
List<string> names = new List<string>()
{
"alice",
"bob",
"curt"
};
//initialize jagged array
string[][] modifiedNames = new string[names.Count][];
//iterate over all names in "names" list
foreach(string name in names)
{
int nameIndex = names.IndexOf(name);
//initialize lower level of array
modifiedNames[nameIndex] = new string[name.Length];
//create variations of a given name
for (int i = 0; i < name.Length; i++)
{
string newName = name.Substring(0, i) + name.Substring(i + 1);
if (modNames[nameIndex].Contains(newName) == false)
modNames[nameIndex].Add(newName);
}
modName.Add(name);
}
I've tried several version thereof, both with lists and arrays, but to no avail. The error message I get in this case is
'string[]' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'string[]' could be found (are you missing a using directive or an assembly reference?)
Thanks a lot for your help!
First, that error is telling you that there is no Add() function for an array. As JohnB points out, a List would probably be a better fit here.
Second, I don't like the string[][] anyway. I'd use IDictionary<string, IList<string>>, storing your original name as the key, and the modified names as the value. That way the original and modified versions are stored together and you don't need to cross reference names with modifiedNames (one of which is a List and the other (currently) an array).
IDictionary<string, IList<string>> names = new Dictionary<string, IList<string>>();
names.Add("alice", new List<string>());
names.Add("bob", new List<string>());
names.Add("curt", new List<string>());
foreach (KeyValuePair<string, IList<string>> name in names)
{
for (int i = 0; i < name.Key.Length; i++)
{
string newName = name.Key.Substring(0, i) + name.Key.Substring(i + 1);
if (!name.Value.Contains(newName))
{
name.Value.Add(newName);
}
}
}
Hope this helps.
How about using a list of lists (of string) while you are working in the method and then converting it into an array of array before returning? Or even just returning a list of list, if the return type is not set in stone?
Here is a suggestion:
var names = new List<string>()
{
"alice",
"bob",
"curt"
};
var nameVariations = new List<List<string>>();
foreach (var name in names)
{
var variationsOfName = new List<string>();
for (int i = 0; i < name.Length; i++)
{
var newName = name.Substring(0, i) + name.Substring(i + 1);
if (!variationsOfName.Contains(newName))
{
variationsOfName.Add(newName);
}
}
nameVariations.Add(variationsOfName);
}
return nameVariations.Select(variationsOfName => variationsOfName.ToArray()).ToArray();
Note: for this to compile you'll need to add Linq (using System.Linq;).
I would do this in two steps. First, write a simple method that will get a list of name variations for a single name. We can simplify the code using some System.Linq extension methods, like Select() and ToList(). The Select statement below treats the string as a character array, and for each character t at index i, it selects the substring from name up to that character and adds the substring from name after that character, returning an IEnumerable<string>, which we create a new List<string> from. Then we finally add the original name to the list and return it:
public static List<string> GetNameVariations(string name)
{
var results = name.Select((t, i) =>
name.Substring(0, i) + name.Substring(i + 1, name.Length - (i + 1)))
.ToList();
results.Add(name);
return results;
}
And then we can use this method to get a List<List<string>> of names from a list of names using another method. Here we are calling GetNameVariations for each name in names (which returns a new List<string> for each name), and returning these lists in a new List<List<string>>:
public static List<List<string>> GetNameVariations(List<string> names)
{
return names.Select(GetNameVariations).ToList();
}
In use, this might look like (using your example):
private static void Main()
{
var names = new List<string> {"bob", "alice", "curt"};
foreach (var nameVariations in GetNameVariations(names))
{
Console.WriteLine(string.Join(", ", nameVariations));
}
GetKeyFromUser("\nDone! Press any key to exit...");
}
Output
You can simplify your logic by using String.Remove(i, 1) to remove one character at a time, iterating over values of i for the length of the string. You can write your query as a one-liner:
var result = names.Select(name => name.Select((_, i) => name.Remove(i, 1)).Reverse().Concat(new[] { name }).ToList()).ToList();
Reformatted for readability:
var result = names
.Select(name =>
name.Select((_, i) => name.Remove(i, 1))
.Reverse()
.Concat(new[] { name })
.ToList())
.ToList();
I think this is a fairly simple way to go:
List<string> names = new List<string>()
{
"alice",
"bob",
"curt"
};
string[][] modifiedNames =
names
.Select(name =>
Enumerable
.Range(0, name.Length)
.Select(x => name.Substring(0, x) + name.Substring(x + 1))
.Concat(new [] { name })
.ToArray())
.ToArray();
That gives:

How define a string array list?

I'd like to define a list whose element is a 3-elements array. Below codes seems ok:
List<dynamic[]> bb = null;
but when I try:
List<dynamic[3]> bb = null;
It throws error. Sure I can create a class/struct for that. But is there a way to define it directly?
Here is one way:
var list = new List<string[]>();
list.Add(new string[3] { "1", "2", "3" });
list.Add(new string[2] { "1", "2" });
Update:
#Ilya's answer shows a solution with dynamic, but I advise you against using dynamic. If you know the structure of the objects create a class or use a tuple, e.g.
var list = new List<(int id, string name, uint reputation)>();
list.Add((298540, "xiaoyafeng", 11));
list.Add((2707359, "Ilya", 3576));
list.Add((581076, "tymtam", 4421));
list.Add((3043, "Joel Coehoorn", 294378));
I'm not sure what your issue was; your title talks about a "string array list", but your posted code describes a list of arrays of dynamic.
I'm not sure I'll ever have reason to create a list of arrays of dynamic, but to show that the code that you discussed in your post can work, this works for me:
var stuff = new List<dynamic[]>
{
new dynamic[] {1, "string"},
new dynamic[] {DateTime.Now, 45.0}
};
But, as noted in other answers, dynamic is a great answer to several classes of questions. But, it's not the right answer here. The right answer to the title of your question (not the description) will use a list of string arrays (as has been pointed in the other answers:
var otherStuff = new List<string[]>
{
new string[] {"Now", "Is", "the", "time"},
new string[] {"for all", "good men, etc."}
};
It seems that you need something like this:
List<dynamic[]> bb = new List<dynamic[]>();
bb.Add(new dynamic[3]); // here you add a 3-element array
bb.Add(new dynamic[3] { "a", "b", "c" }); // here you add another one 3-element array
// List containing a string array with 3 nulls in it
var aa = new List<string[]> {new string[3]};
// List containing a string array with 3 strings in it
var bb = new List<string[]> {new[] {"a", "b", "c"}};

How do I remove duplicates from excel range? c#

I've converted cells in my excel range from strings to form a string list and have separated each item after the comma in the original list. I am starting to think I have not actually separated each item, and they are still one whole, trying to figure out how to do this properly so that each item( ie. the_red_bucket_01)is it's own string.
example of original string in a cell 1 and 2:
Cell1 :
the_red_bucket_01, the_blue_duck_01,_the green_banana_02, the orange_bear_01
Cell2 :
the_purple_chair_01, the_blue_coyote_01,_the green_banana_02, the orange_bear_01
The new list looks like this, though I'm not sure they are separate items:
the_red_bucket_01
the_blue_duck_01
the green_banana_02
the orange_bear_01
the_red_chair_01
the_blue_coyote_01
the green_banana_02
the orange_bear_01
Now I want to remove duplicates so that the console only shows 1 of each item, no matter how many there are of them, I can't seem to get my foreah/if statements to work. It is printing out multiple copies of the items, I'm assuming because it is iterating for each item in the list, so it is returning the data that many items.
foreach (Excel.Range item in xlRng)
{
string itemString = (string)item.Text;
List<String> fn = new List<String>(itemString.Split(','));
List<string> newList = new List<string>();
foreach (string s in fn)
if (!newList.Contains(s))
{
newList.Add(s);
}
foreach (string combo in newList)
{
Console.Write(combo);
}
You probably need to trim the strings, because they have leading white spaces, so "string1" is different from " string1".
foreach (string s in fn)
if (!newList.Contains(s.Trim()))
{
newList.Add(s);
}
You can do this much simpler with Linq by using Distinct.
Returns distinct elements from a sequence by using the default
equality comparer to compare values.
foreach (Excel.Range item in xlRng)
{
string itemString = (string)item.Text;
List<String> fn = new List<String>(itemString.Split(','));
foreach (string combo in fn.Distinct())
{
Console.Write(combo);
}
}
As mentioned in another answer, you may also need to Trim any whitespace, in which case you would do:
fn.Select(x => x.Trim()).Distinct()
Where you need to contain keys/values, its better to use Dictionary type. Try changing code with List<T> to Dictionary<T>. i.e.
From:
List<string> newList = new List<string>();
foreach (string s in fn)
if (!newList.Containss))
{
newList.Add(s);
}
to
Dictionary<string, string> newList = new Dictionary<string, string>();
foreach (string s in fn)
if (!newList.ContainsKey(s))
{
newList.Add(s, s);
}
If you are concerned about the distinct items while you are reading, then just use the Distinct operator like fn.Distinct()
For processing the whole data, I can suggest two methods:
Read in the whole data then use LINQ's Distinct operator
Or use a Set data structure and store each element in that while reading the excel
I suggest that you take a look at the LINQ documentation if you are processing data. It has really great extensions. For even more methods, you can check out the MoreLINQ package.
I think your code would probably work as you expect if you moved newList out of the loop - you create a new variable named newList each loop so it's not going to find duplicates from earlier loops.
You can do all of this this more concisely with Linq:
//set up some similar data
string list1 = "a,b,c,d,a,f";
string list2 = "a,b,c,d,a,f";
List<string> lists = new List<string> {list1,list2};
// find unique items
var result = lists.SelectMany(i=>i.Split(',')).Distinct().ToList();
SelectMany() "flattens" the list of lists into a list.
Distinct() removes duplicates.
var uniqueItems = new HashSet<string>();
foreach (Excel.Range cell in xlRng)
{
var cellText = (string)cell.Text;
foreach (var item in cellText.Split(',').Select(s => s.Trim()))
{
uniqueItems.Add(item);
}
}
foreach (var item in uniqueItems)
{
Console.WriteLine(item);
}

How to add string to an array list in c#

I have a list and a string
var Resnames= new List<string>();
string name = "something";
I want to append string to it like
Resnames += name;
How can I do it
Since you are using List (not a legacy fixed-size array) you able to use List.Add() method:
resourceNames.Add(name);
If you want to add an item after the instantiation of a list instance you can use object initialization (since C# 3.0):
var resourceNames = new List<string> { "something", "onemore" };
Also you might find useful List.AddRange() method as well
var resourceNames = new List<string>();
resourceNames.Add("Res1");
resourceNames.Add("Res2");
var otherNames = new List<string>();
otherNames.AddRange(resourceNames);
Just as simple as that:
Resnames.Add(name);
BTW: VisualStudio is your friend! By typing a . after Resnames it would have helped you.
try adding the string to array list like this,
var Resnames= new List<string>();
string name = "something";
Resnames.Add(name);
foreach (var item in Resnames)
{
Console.WriteLine(item);
}
Add String to List this way:
var ListName = new List<string>();
string StringName = "YourStringValue";
ListName.Add(StringName);

Categories

Resources