ASP.NET add item to array - c#

I have this array defined:
string[] emailAddress = {};
What I am trying to do is add items to this array like so:
emailAddress[] = de.Properties["mail"][0].ToString();
and I get a cannot convert string to array error. How do I add an item to an array?

string[] emailAddress = new string[1]; // initialize it to a length of 1
emailAddress[0] = de.Properties["mail"][0].ToString(); // assign the string to position 1
If you do not know the length at runtime then use a generic List and convert it afterwards.
var emailAddress = new List<string>();
emailAddress.Add(de.Properties["mail"][0].ToString());
var myArray = emailAddress.ToArray(); // create an array from the list
I recommend you read this article on how to work with arrays in c# (or some other tutorial).
https://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

Based on your comment that it has to be an array and can't be a List, this might be what you need.
Instantiate the array with a specific length. Something like this
string[] emailAddress = new string[emailAddressde.Properties["mail"].Length];
Then you can loop through with something like
for (var i = 0; i < de.Properties["mail"].Length; i++)
emailAddress[i] = de.Properties["mail"][i].ToString();
to populate your emailAddress array.

You have to initialize your array first with a fixed size:
string[] emailAddress = new string[5]; // array with 5 items
and then you can add items like this:
emailAddress[0] = de.Properties["mail"][0].ToString();
But consider if somehow possible using a List<string> which is much more flexible.

You need to reference a location in your array, what you are trying to do is assign your value as the array.
emailAddress[0] = de.Properties["mail"][0].ToString();

If you know how big your array will be then you can init the array to a static size. For example if you know that the array of email will only every be 2 items (index 0 and 1) then you can init the array to that size like this
string[] emailAddress = string[2];
if the items in the array are unknown (how many email addresses) the you should using something else like
List emailAddresses = new List();
So something like this:
List<string> emailAddresses = new List<string>();
emailAddresses.Add("youremail#mail.com");
emailAddresses.ToArray();

Related

C# Split - Split on list dont return all the wanted strings

I'm fairly new to C#, and i've come across a problem trying to split on list elements.
I have a resource file containing string properties as such:
ResourceFile
ResourceFile
I've collected them in a List as:
public List<String> RawNewsList1 = new List<String>()
{
{Resource.NewsContentAndroid1},
{Resource.NewsMetaAndroid1},
};
I'm trying to split on the semicolons but only get results from my second list item.
My split look like this:
public void FilterRawNews()
{
String[] seperator = { ";;;" };
String[] filteredList1 = { "" };
for (int i = 0; i < RawNewsList1.Count; i++) {
filteredList1 = RawNewsList1[i].Split(seperator, 5,
StringSplitOptions.RemoveEmptyEntries);
}
foreach (String s in filteredList1)
{
Console.WriteLine(s);
}
}
Its only prints:
110
2.8
02-07-2020
What am i doing wrong?
Thanks in advance!
The filteredList1 variable is first filled with data from your the first resource, then at the next loop the variable's content is replaced with the data coming from the second resource.
You can use a List<string> instead that has the AddRange method to continuosly add elements to the list
List<string> filteredList1 = new List<string>();
for (int i = 0; i < RawNewsList1.Count; i++) {
filteredList1.AddRange(RawNewsList1[i].Split(seperator, 5,StringSplitOptions.RemoveEmptyEntries));
}
From this we could simplify the code to one-liner with
filteredList = RawNewsList1.SelectMany(a => a.Split(seperator,5, StringSplitOptions.RemoveEmptyEntries)).ToList();
So, what's happen in that single line? That syntax is used when you work with objects that can be treated as a sequence of data. In this context your array RawNewsList1 is a sequence of data and we can use the IEnumerable extensions brought to us by using the Linq namespace. The SelectMany extension requires a lambda expression ( a => ....) that is used to produce the instructions where each element of the sequence (a) is passed to an expression that returns another sequence of data (the array returned by Split). The sequence returned is accumulated to the sequence produced by the next elements from the original RasNewsList1. Finally the accumulated sequence is materialized with the call to ToList()
You are overwriting filteredList1 in each iteration.
That is why you only get the last result.
Just declare filteredList1 as a list and and use AddRange().
Edit: or use LINQ:
var raw = new List<string>() { "111;;;222", "333;;;444" };
String[] seperator = { ";;;" };
var filterlist1 = raw.SelectMany(r => r.Split(seperator, 5, StringSplitOptions.RemoveEmptyEntries)).ToList();

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>>.

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[]>();

C# Declare multiple dynamically named variables [duplicate]

This question already has answers here:
How do I name variables dynamically in C#?
(9 answers)
Closed 8 years ago.
I'm not sure of the wording of what I'm looking for so I apologize if this has been answered since I'm new to C#.
What I'm trying to do is create multiple dynamically-named Lists based off of "i".
A code snippet would like this:
List<string> infoForUserSessions = new List<string>();
// Code that adds data to infoForUserSessions
for (int i = 0; i < infoForUserSessions.Count; i++){
// I want to initialize multiple List variables based off of how many users were found in my "infoForUserSessions" List.
List<string> user[i];
}
I was hoping it would create new Lists named:
user1
user2
user3
etc.
Update Sorry all for being so confusing. You guys swarmed with answers! Let me be more specific. I'm practicing string output from a Console application such as using "PsExec \localhost qwinsta". The output would look like this:
SESSIONNAME USERNAME ID STATE TYPE DEVICE
services 0 Disc
>console mariob 1 Active
rdp-tcp 65536 Listen
Each line is stored in the List "infoForUserSessions" so the data looks like:
infoForUserSessions[0] = services 0 Disc
infoForUserSessions[1] = >console mariob 1 Active
infoForUserSessions[2] = rdp-tcp 65536 Listen
I then have code to pick out the important text out of each array index:
string[] tempStringArray;
List<string> allUsersAndIDs = new List<string>();
char[] delimiters = new char[] { ' ' };
foreach (string line in infoForUserSessions)
{
tempStringArray = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < tempStringArray.Length; i++)
{
// This is where I was thinking of some logic to create a new array for each user so I could store the separate parts of a string into this new array
// Something like (which would be from the Lists above in my original message--this is based off of how many users were stored in the original infoForUserSessions List:
// user1.Add(i);
}
}
I'm still working out the logic but I figured I wanted the output to be something dynamic based off of two factors:
How many "users" (strings) were stored in the List infoForUserSessions
Individual user arrays/Lists that have their own index values of:
.
user1[0] = "services";
user1[1] = "0";
user1[2] = "Disc";
user2[0] = ">console";
user2[1] = "mariob";
user2[2] = "1";
user2[2] = "Active";
Don't try to use dynamically named variables. That's simply not how variables work in C#.
Use an array of lists:
List<string>[] user = new List<string>[infoForUserSessions.Count];
for (int i = 0; i < infoForUserSessions.Count; i++) {
user[i] = new List<string>();
}
If the number of sessions can change, you would use a List<List<string>> instead, so that you can add lists to it when you add items to the infoForUserSessions list.
You can use Dictionary<String, List<string>>
Dictionary associate a key to a value, like an physical Dictionary book.
Dictionary<String, List<string>> myDict = new Dictionary<String, List<string>>();
for (int i = 0; i < infoForUserSessions.Count; ++i){
myDict.add("user" + i, new List<string>());
}
Here is an exemple how to use Dictionary :
Dictionary<String, String> myDict = new Dictionary<String, String>();
//Line below will add both KEY and a VALUE to the dictionary, BOTH are linked one to eachother
myDict.add("apple", "Apple is a brand");
//This above line return "Apple is a brand"
myDict["apple"];

Populate list from array

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?

Categories