Populate list from array - c#

if i have an array. can i populate a generic list from that array:
Foo[] fooList . . . (assume populated array)
// This doesn't seem to work
List<Foo> newList = new List<Foo>(fooList);

You could convert the array to a List:
string[] strings = { "hello", "world" };
IList<string> stringList = strings.ToList();

You are looking for List(t).AddRange Method

As #korki said, AddRange will work, but the code you've posted should work fine. For example, this compiles:
var i = new int[10];
var list = new List<int>(i);
Could you show us more of your code?

Related

How to generate a random list of strings from an array

I want to generate a random list of 5 string values from an array of string.
type options. I have an string[] called 'Items':
private static string[] Items = new[]
{
"Widgets", "Wotsits", "Grommits"
};
Using the options in this array, I want to instantiate a List<string> collection with 5 random strings. I am trying to do it like this:
public List<string> List()
{
var r = new Random();
return Enumerable.Range(1, 5).Select(index => new List<string>()
{
Items[r.Next(Items.Length)]
});
}
I cannot get it to work. One problem I have is I use Enumerable.Range but this creates a type error which I have been unable to solve with .ToList().
Is there a way to do it?
Inside your Select statement you are creating a new list for each iteration, each list with one random element. Just remove the new List<string>(){...} part and simply write Items[rng.Next(Items.Length)].
This way you will get a List<string> instead of a List<List<string>>.

How to use items of an array as names for other variables c#

I have a list of names in an array and i would like to use these names to assign them to new lists like bellow:
var list = new string[]{"bot1","bot2","bot3"};
List<string> list[0] = new List<string>();
but i am getting the error: a local variable or function named 'list' is already defined in this scope.
is there a work around !!?
your input will be greatly appreciated.
I think you can store your bots in dictionary:
var bots = new Dictionary<string,List<string>>();
bots[name] = new List<string>();
bots[name].Add("some str");
If you only need a integer as key than you can also use this solution.
List<List<string>> list = new List<List<string>>();
list.Add(new List<string>{ {"A"} });
list[0][0] = "..";

C# list of array type

I want to create a list of array type.
I want to create array containing values :
array = [a,b];
Then i want to put this array in list :
List<Array> list = new List<Array>( );
I am able to do this with list of string type but no luck with array type :
List<String> list = new List<String>( );
I am from javascript background, not much familiar with concept of collections in c#.
Also how can i create array in c# like we do in javascript :
var arrTemp = ["a", "b"];
Well, since your array is string[]:
var arrTemp = ["a", "b"];
you have to declare the required list as List<string[]>:
// list of string arrays
List<string[]> list = new List<string[]>() {
new string[] {"a", "b"}
};
In case you want to be able to put any array into the list declare it as loose as possible (List<object[]>):
// list of abitrary arrays
List<object[]> list = new List<object[]>() {
new string[] {"a", "b"},
new double[] {123.45, 789.12, 333.55},
new object[] {'a', "bcd", 1, 244.95, true},
};
Hope this can help you
var test = new List<int[]>();
You can actually create a list of arrays:
var listOfArrays = new List<Array>();
The problem with this is that it's difficult to use the arrays themselves, as the Array type doesn't support array syntax. (e.g. You can't do listOfArrays[0][0]) Instead, you have to use the GetValue method to do your retrieval:
var obj = listOfArrays[0].GetValue(0);
But this has another problem. The GetValue method returns object, so while you could always cast it to the desired type, you lose your type safety in choosing this approach.
Alternatively, you could just store object[] arrays:
var listOfArrays = new List<object[]>();
var obj = listOfArrays[0][0];
But while this solves the issue of the array notation, you still lose the type safety.
Instead, if at all possible, I would recommend finding a particular type, then just have arrays of that type:
var listOfArrays = new List<string[]>();
string s = listOfArrays[0][0];
for example, an array of strings would be
var arrayOfString = new string[]{"a","b"};
// or shorter form: string[] arrayOfString = {"a","b"};
// also: var arrayOfString = new[] { "a", "b" }
And then creating a list-of-arrayOfString would be
var listOfArrayOfString = new List<string[]>();
This works with any type, for example if you had a class MyClass
var arrayOfMyClass = new MyClass[]{ ... }; // ... is you creating instances of MyClass
var list = new List<MyClass[]>();

Finding whether an element available in GenericList

I have a string[] which contains value {"data1","data2","data3"}.
and i have a GenericList which contains
data2
data4
two records
i want to get the common datas which is avail in string[] and the genericList
Have you tried something like
string[] s = {"data1", "data2", "data3"};
List<string> list = new List<string> { "data2", "data3" };
var commonList = list.Intersect(s);
Have a look at Enumerable.Intersect Method (IEnumerable, IEnumerable)
Assuming it's a List<string> and you're using .NET 3.5 or higher, you can use the Intersect method from LINQ to Objects:
var intersection = stringArray.Intersect(stringList);
Note that this will return a lazily-evaluated IEnumerable<string>. If you need it in an array or a list, call the relevant method:
var intersectionArray = stringArray.Intersect(stringList).ToArray();
// or
var intersectionList = stringArray.Intersect(stringList).ToList();
Also note that this is a set operation - so the result will not contain any duplicates, even if there is duplication of a particular element in both the original collections.
Take a look at the Intersect extension method here
string[] c1 = { "data1", "data2", "data3" };
string[] c2 = { "data2", "data4" };
IEnumerable<string> both = c1.Intersect(c2);
foreach (string s in both) Console.WriteLine(s);
Will print data2.

Clear array of strings

What is the easiest way to clear an array of strings?
Have you tried Array.Clear?
string[] foo = ...;
Array.Clear(foo, 0, foo.Length);
Note that this won't change the size of the array - nothing will do that. Instead, it will set each element to null.
If you need something which can actually change size, use a List<string> instead:
List<string> names = new List<string> { "Jon", "Holly", "Tom" };
names.Clear(); // After this, names will be genuinely empty (Count==0)
Array.Clear(theArray, 0, theArray.Length);
It depends on circumstance (like: what is in the array) but the best method usually is to create a new one. Dropping all references to the old one.
MyType[] array = ...
....
array = new MyType[size];
I think you can also get away with this for example:
SearchTerm = new string[]{};
You can try this.
result = result.Where(x => !string.IsNullOrEmpty(x)).ToArray();
string[] foo;
foo = string[""];
how about
string[] foo;
foo = null;

Categories