Creating a List<string> containing a single string N times - c#

Is there any way to construct a list of type List<string> which contains a single string N times without using a loop? Something similar to String(char c, int count) but instead for List of strings.
List<string> list = new List<string>() { "str", "str", "str", ..... N times };

You can use Repeat():
List<String> l = Enumerable.Repeat<String>("foo", 100).ToList<String>();
It will still use a loop of course, but now you don't "see" it.

Try doing this:
List<String> list = new List<String>();
for(int i=0; i<N; i++)
{
list.add("str");
}

Related

how to create a loop that creates lists

I want to create a loop that makes lists the name of the lists that need to come from another list.
I tried doing it like that.
for (int i = 0; i < Names.Count; i++)
{
List<string> Name[i] = new List<string>();
}
Just pass the source collection in the list constructor, like this
var newList = new List<string>(Names);
If you want more control, you can still do your loop, but declare the destination list first:
var newList = new List<string>();
for (int i = 0; i < Names.Count; i++)
{
newList.Add(Names[i]);
}
And finally, if you need a list of lists, where each list is named, you'd use a different data structure, for example a Dictionary<string, List<string>> instead:
var listOfLists = new Dictionary<string, List<string>>();
for (int i = 0; i < Names.Count; i++)
{
listOfLists.Add(
Names[i], // <--- the name of the list is the key
new() // <--- the named list (initially empty)
);
}
Which, in modern C#, can be shortened further to become
var listOfLists = Names.ToDictionary(name => name, _ => new List<string>());

How can I split a string to store contents in two different arrays in c#?

The string I want to split is an array of strings.
the array contains strings like:
G1,Active
G2,Inactive
G3,Inactive
.
.
G24,Active
Now I want to store the G's in an array, and Active or Inactive in a different array. So far I have tried this which has successfully store all the G's part but I have lost the other part. I used Split fucntion but did not work so I have tried this.
int i = 0;
for(i = 0; i <= grids.Length; i++)
{
string temp = grids[i];
temp = temp.Replace(",", " ");
if (temp.Contains(' '))
{
int index = temp.IndexOf(' ');
grids[i] = temp.Substring(0, index);
}
//System.Console.WriteLine(temp);
}
Please help me how to achieve this goal. I am new to C#.
If I understand the problem correctly - we have an array of strings Eg:
arrayOfStrings[24] =
{
"G1,Active",
"G2,Inactive",
"G3,Active",
...
"G24,Active"
}
Now we want to split each item and store the g part in one array and the status into another.
Working with arrays the solution is to - traverse the arrayOfStrings.
Per each item in the arrayOfStrings we split it by ',' separator.
The Split operation will return another array of two elements the g part and the status - which will be stored respectively into distinct arrays (gArray and statusArray) for later retrieval. Those arrays will have a 1-to-1 relation.
Here is my implementation:
static string[] LoadArray()
{
return new string[]
{
"G1,Active",
"G2,Inactive",
"G3,Active",
"G4,Active",
"G5,Active",
"G6,Inactive",
"G7,Active",
"G8,Active",
"G9,Active",
"G10,Active",
"G11,Inactive",
"G12,Active",
"G13,Active",
"G14,Inactive",
"G15,Active",
"G16,Inactive",
"G17,Active",
"G18,Active",
"G19,Inactive",
"G20,Active",
"G21,Inactive",
"G22,Active",
"G23,Inactive",
"G24,Active"
};
}
static void Main(string[] args)
{
string[] myarrayOfStrings = LoadArray();
string[] gArray = new string[24];
string[] statusArray = new string[24];
int index = 0;
foreach (var item in myarrayOfStrings)
{
var arraySplit = item.Split(',');
gArray[index] = arraySplit[0];
statusArray[index] = arraySplit[1];
index++;
}
for (int i = 0; i < gArray.Length; i++)
{
Console.WriteLine("{0} has status : {1}", gArray[i] , statusArray[i]);
}
Console.ReadLine();
}
seems like you have a list of Gxx,Active my recomendation is first of all you split the string based on the space, which will give you the array previoulsy mentioned doing the next:
string text = "G1,Active G2,Inactive G3,Inactive G24,Active";
string[] splitedGItems = text.Split(" ");
So, now you have an array, and I strongly recommend you to use an object/Tuple/Dictionary depends of what suits you more in the entire scenario. for now i will use Dictionary as it seems to be key-value
Dictionary<string, string> GxListActiveInactive = new Dictionary<string, string>();
foreach(var singleGItems in splitedGItems)
{
string[] definition = singleGItems.Split(",");
GxListActiveInactive.Add(definition[0], definition[1]);
}
What im achiving in this code is create a collection which is key-value, now you have to search the G24 manually doing the next
string G24Value = GxListActiveInactive.FirstOrDefault(a => a.Key == "G24").Value;
just do it :
var splitedArray = YourStringArray.ToDictionary(x=>x.Split(',')[0],x=>x.Split(',')[1]);
var gArray = splitedArray.Keys;
var activeInactiveArray = splitedArray.Values;
I hope it will be useful
You can divide the string using Split; the first part should be the G's, while the second part will be "Active" or "Inactive".
int i;
string[] temp, activity = new string[grids.Length];
for(i = 0; i <= grids.Length; i++)
{
temp = grids[i].Split(',');
grids[i] = temp[0];
activity[i] = temp[1];
}

how to count an element in each index of Arraylist in c#

First, I have a string that contain all of characters and then I add it into Arraylist of list1 but I separate it with *. so now I have 5 elements of arraylist.
String fString = "DAVCFW_ACK*DAVCFW_20_30_90*DAVCFW_15.5_20.1_35.0*DAVCFW_40_230_110*DAVCFW_END";
ArrayList list1 = new ArrayList();
string[] words = fString.Split('*');
foreach (string s in words)
{
list1.Add(s);
}
Second, I delete first 6 charecters of each elements and keep it into Arraylist of list2.
ArrayList list2 = new ArrayList();
String s1 = list1.ToString();
foreach(string s in list1){
for (int i = 0; i < s.Length; i++ ){
if(i>6){
list2[i-7] = list1[i];
}
}
}
Third, I delete all _ characters of each elemeant and keep it into Arraylist of list3. Now I get only number not characters.
ArrayList list3 = new ArrayList();
String[] word_s1 = s1.Split('_');
foreach(string s in word_s1){
list3.Add(s);
}
And then I would like to keep the value of list3 like matrix but still is an Arraylist. I need to know number of element in each index of list3 to define row and colomn. For column I think I can use list3.count; but for row I don't know how. After I know row. I have to put 0 to element in each index that have number of row less than row.
Pleas Help me. Thanks you.
Did you ever run this code? First of all it doesn't work, because in second listing you are trying to get list1[7], where last index is 5. Second, in the same listing you are accesing element in subloop, not characters. Third, why did you do that String s1 = list1.ToString()? s1 is equal to string "System.Collections.ArrayList".
Back to your question. If you want to get length of every row, just use string.Length property. Here is working code:
String fString = "DAVCFW_ACK*DAVCFW_20_30_90*DAVCFW_15.5_20.1_35.0*DAVCFW_40_230_110*DAVCFW_END";
ArrayList list1 = new ArrayList();
string[] words = fString.Split('*');
foreach (string s in words)
{
list1.Add(s);
}
ArrayList list2 = new ArrayList();
foreach(string s in list1)
{
list2.Add(s.Substring(6));
}
ArrayList list3 = new ArrayList();
foreach (string s in list2)
{
list3.Add(s.Replace("_", string.Empty));
}
foreach (string s in list3)
{
Console.WriteLine(s);
}
Console.WriteLine("Number of rows: {0}", list3.Count);
for (int i = 0; i < list3.Count; i++)
{
Console.WriteLine("Number of characters in {0} row: {1}",i, (list3[i] as string).Length);
}
The question is not very clear about what you want. If you are after a matrix of item position as column, and values as rows, you can try something like this.
String fString = "DAVCFW_ACK*DAVCFW_20_30_90*DAVCFW_15.5_20.1_35.0*DAVCFW_40_230_110*DAVCFW_END";
Dictionary<int, ArrayList> matrix = new Dictionary<int,ArrayList>();
string[] words = fString.Split('*');
for (int i = 0; i < words.Length - 2 ; i++) // exclude the first and the last words because they do not have number
{
string[] numbers = words[i+1].Substring(6).Split('_');
ArrayList list = new ArrayList();
for (int j = 1; j < numbers.Length; j++) // exlcude the first number as it is empty string
{
list.Add(numbers[j]);
}
matrix[i] = list;
}

Can't create nested list because list.Clear doesn't seem to work as I want

I try to load txt file that consists of 200 rows each of different length into nested list so that every sublist inside main list will be equal to row, so there will be 200 sublists.
class MainClass
{
public static void Main (string[] args)
{
List<List<int>> arrayList = new List<List<int>>();
List<int> tmp = new List <int> ();
string[] file = File.ReadAllLines(#"C:\file.txt");
foreach (string line in file) {
string[] linef = line.Split (new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
tmp.Clear ();
for (int n = 0; n < linef.Length; n++) {
tmp.Add (int.Parse (linef [n]));
}
arrayList.Add (tmp);
}
But arrayList seams to contain only last row - whenever i try to get some number, for a example arrayList[78][5], it gives me 5th number from 200th row no matter what the first index is - 78 or other. I think there is issue with tmp.Clear but i cant figure out how to make it work.
Because you are re-adding the same List<int> tmp many times to arrayList, so that at the end
bool areSame = object.ReferenceEquals(arrayList[0], arrayList[1]); // true
You have one List<int> with n references to it (one for each "row" of arrayList)
Change it to:
foreach (string line in file) {
List<int> tmp = new List <int> ();
// No Clear necessary
tmp.Clear() makes your list empty, that is all. The main list contains only 200 references to your tmp list.
You have to call
tmp = new List<int>();
instead of
tmp.Clear();

How to add a collection of list into a list?

I have my code like,
List<string> list = new List<string>();
model.QuestionSetList = new List<string>();
for (int i = 0; i < response.QuestionsInfoList.Count(); i++)
{
list.Add(response.QuestionSetInfo.QuestionsInfoList[i].Question);
foreach (AnswerSetContract answerSetContract in response.QuestionsInfoList[i].AnswersInfoList)
{
list.Add(answerSetContract.AnswerText);
}
model.QuestionSetList.Add(list)
}
I cannot add a list into another list.Kindly tell me what to do in this case.
Look at the Concat function within the System.Linq namespace
I.e.
using System.Linq;
List<string> list = new List<string>();
model.QuestionSetList = new List<string>();
for (int i = 0; i < response.QuestionsInfoList.Count(); i++)
{
list.Add(response.QuestionSetInfo.QuestionsInfoList[i].Question);
foreach (AnswerSetContract answerSetContract in response.QuestionsInfoList[i].AnswersInfoList)
{
list.Add(answerSetContract.AnswerText);
}
model.QuestionSetList = model.QuestionSetList.Concat(list);
}
But why not at the place of; list.Add(answerSetContract.AnswerText); add it directly to model.QuestionSetList?
So like this;
List<string> list = new List<string>();
model.QuestionSetList = new List<string>();
for (int i = 0; i < response.QuestionsInfoList.Count(); i++)
{
list.Add(response.QuestionSetInfo.QuestionsInfoList[i].Question);
foreach (AnswerSetContract answerSetContract in response.QuestionsInfoList[i].AnswersInfoList)
{
model.QuestionSetList.Add(answerSetContract.AnswerText);
}
}
If you want a List of Lists, then your QuestionSetList would have to be:
model.QuestionSetList = new List<List<<string>>()
Consider creating a custom type though, otherwise it's a bit like inception, list in a list in a list in a list.........
Or if you're actually wanting to combine the Lists, then use Concat:
list1.Concat(list2);
You should try with AddRange, it allows to add a collection to a List
http://msdn.microsoft.com/en-us/library/z883w3dc.aspx
model.QuestionSetList is a list of strings.
You're trying to add a list of strings to it. As their types are incompatible, it won't allow you to do that.
Try making model.QuestionSetList a List<List<string>> and see if that helps you.

Categories