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"}};
Related
For example;
List<string> list = new List<string>{
"1[EMPTY]", "2[EMPTY]", "3[EMPTY]", "4[EMPTY]", "5[EMPTY]", "6[EMPTY]", "7[EMPTY]", "8[EMPTY]", "9[EMPTY]", "10[EMPTY]", "11[EMPTY]", "12[EMPTY]"
};
When I use
list.Sort();
Output:
1[EMPTY] 10[EMPTY] 11[EMPTY] 12[EMPTY] 2[EMPTY] 3[EMPTY] 4[EMPTY] 5[EMPTY] 6[EMPTY] 7[EMPTY] 8[EMPTY] 9[EMPTY]
I want 1-2-3-4-5-6-7-8-9-10-11-12.
How can i solve this problem?
(Sorry my English is bad :{)
You can use OrderBy. Basically trick is to sort the string so parsing as int. and getting the value till the first occurance of [.
List<string> list = new List<string>{
"1[EMPTY]", "2[EMPTY]", "3[EMPTY]", "4[EMPTY]", "5[EMPTY]", "6[EMPTY]", "7[EMPTY]", "8[EMPTY]", "9[EMPTY]", "10[EMPTY]", "11[EMPTY]", "12[EMPTY]"
};
list = list.OrderBy(c => int.Parse(c.Substring(0, c.IndexOf('[')))).ToList();
I need to get the index of one array elements in another array using LINQ
The following are my two array:
string[] arr1 = new string[] { "Albany", "Albuquerque", "Anchorage", "Atlantic City",
"Baton Rouge", "Biloxi", "CEDAR SPRINGS", "Chicago", "Columbia", "Columbus" };
string[] arr2 = new string[] { "Albany", "Biloxi" };
Can anybody help me out on the same?
You can use Array.IndexOf:
int[] indicesOf2In1 = arr2.Select(s => Array.IndexOf(arr1, s)).ToArray(); // (0,5)
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.
I'm trying to grab a single item from each of the Lists here, and combine them to make a unique name. This is just for kicks. :)
Here are the lists:
List<string> FirstNames = new List<string>()
{
"Sergio",
"Daniel",
"Carolina",
"David",
"Reina",
"Saul",
"Bernard",
"Danny",
"Dimas",
"Yuri",
"Ivan",
"Laura"
};
List<string> LastNamesA = new List<string>()
{
"Tapia",
"Gutierrez",
"Rueda",
"Galviz",
"Yuli",
"Rivera",
"Mamami",
"Saucedo",
"Dominguez",
"Escobar",
"Martin",
"Crespo"
};
List<string> LastNamesB = new List<string>()
{
"Johnson",
"Williams",
"Jones",
"Brown",
"David",
"Miller",
"Wilson",
"Anderson",
"Thomas",
"Jackson",
"White",
"Robinson"
};
I know I get a single item via an index, and I also know that I can use the Random class to generate a random number from 0 to ListFoo.Count.
What I don't know is how to check if a random permutation has already been drawn from the collections.
I've thought about using the tuple class:
List<Tuple<int,int,int>> permutations = new List<Tuple<int,int,int>>();
But I'm having a brainfart here. ;) Any guidance? I'm not really looking for the entire code to this simple problem, just a suggestion or hint.
EDIT
Thanks to the suggestions given here, here what I've come up with. Any room for improvements?
static void Main(string[] args)
{
List<string> FirstNames = new List<string>()
{
"Sergio",
"Daniel",
"Carolina",
"David",
"Reina",
"Saul",
"Bernard",
"Danny",
"Dimas",
"Yuri",
"Ivan",
"Laura"
};
List<string> LastNamesA = new List<string>()
{
"Tapia",
"Gutierrez",
"Rueda",
"Galviz",
"Yuli",
"Rivera",
"Mamami",
"Saucedo",
"Dominguez",
"Escobar",
"Martin",
"Crespo"
};
List<string> LastNamesB = new List<string>()
{
"Johnson",
"Williams",
"Jones",
"Brown",
"David",
"Miller",
"Wilson",
"Anderson",
"Thomas",
"Jackson",
"White",
"Robinson"
};
var permutations = new List<Tuple<int, int, int>>();
List<string> generatedNames = new List<string>();
Random random = new Random();
int a, b, c;
//We want to generate 500 names.
while (permutations.Count < 500)
{
a = random.Next(0, FirstNames.Count);
b = random.Next(0, FirstNames.Count);
c = random.Next(0, FirstNames.Count);
Tuple<int, int, int> tuple = new Tuple<int, int, int>(a, b, c);
if (!permutations.Contains(tuple))
{
permutations.Add(tuple);
}
}
foreach (var tuple in permutations)
{
generatedNames.Add(string.Format("{0} {1} {2}", FirstNames[tuple.Item1],
LastNamesA[tuple.Item2],
LastNamesB[tuple.Item3])
);
}
foreach (var n in generatedNames)
{
Console.WriteLine(n);
}
Console.ReadKey();
}
You are on the right track!
Every time you generate a name, add it to your tuple list
//Create the tuple
Tuple <int, int, int> tuple = new Tuple<int, int, int>(index1, index2, index3)
if(!permutations.Contains(tuple))
{
permutations.Add(tuple);
//Do something else
}
I would think the simplest solution is to just the stuff the assembled name into a HashSet<string> which will ensure the list of created names is unique.
An alternative to the HashSet answer is to build all of the possible combinations in advance, shuffle them, then store them in a Queue, where you can retrieve them one at a time. This will avoid having to check the existing ones every time you build a new one, and will still be random.
This only works if you don't have a large set to begin with, since the work involved in creating the complete list and shuffling it would be huge for a large set of data.
It's really easy to generate them all using LINQ:
var combs =
(from first in FirstNames
from second in LastNamesA
from third in LastNamesB
select new Tuple<string, string, string>(first, second, third)).ToList();
After this, if you need to take unique elements from the list randomly, just shuffle the list and then pick them one-by-one in order.
You can use the Knuth-Fisher-Yates algorithm (that's an in-place shuffle):
Random rand = new Random();
for (int i = combs.Count - 1; i > 0; i--)
{
int n = rand.Next(i + 1);
var mem = combs[i];
combs[i] = combs[n];
combs[n] = mem;
}
I would create a HashSet<int> and store the numeric representation of the picks (eg 135 for first, third and 5th or use 010305) and then check if they are in the set.
Create a new tuple with 3 random digits
Check if permutations contains your new tuple
If not => Add new tuple to the list. If yes, start with point 1 again.
I am creating a new C# List (List<double>). Is there a way, other than to do a loop over the list, to initialize all the starting values to 0?
In addition to the functional solutions provided (using the static methods on the Enumerable class), you can pass an array of doubles in the constructor.
var tenDoubles = new List<double>(new double[10]);
This works because the default value of an double is already 0, and probably performs slightly better.
You can use the initializer:
var listInt = new List<int> {4, 5, 6, 7};
var listString = new List<string> {"string1", "hello", "world"};
var listCustomObjects = new List<Animal> {new Cat(), new Dog(), new Horse()};
So you could be using this:
var listInt = new List<double> {0.0, 0.0, 0.0, 0.0};
Otherwise, using the default constructor, the List will be empty.
Use this code:
Enumerable.Repeat(0d, 25).ToList();
new List<double>(new double[25]); //Array elements default to 0
One possibility is to use Enumerable.Range:
int capacity;
var list = Enumerable.Range(0, capacity).Select(i => 0d).ToList();
Another is:
int capacity;
var list = new List<double>(new double[capacity]);
A bit late, but maybe still of interest:
Using LINQ, try
var initializedList = new double[10].ToList()
...hopefully avoiding copying the list (that's up to LINQ now).
This should be a comment to Michael Meadows' answer, but I'm lacking reputation.
For more complex types:
List<Customer> listOfCustomers =
new List<Customer> {
{ Id = 1, Name="Dave", City="Sarasota" },
{ Id = 2, Name="John", City="Tampa" },
{ Id = 3, Name="Abe", City="Miami" }
};
from here: David Hayden's Blog