c# change the string in a foreach string loop - c#

I'm trying to cycle through strings in a list with a foreach loop, but I don't know how to change the item that's being referenced - How can I change s in the list... e.g. below I want to add "-" to the end of every string, s in myStringList
foreach(string s in myStringList)
{
s = s + "-";
}
I can't do things to s because it's a "foreach iteration variable" - so can I not change it as I cycle through?
Do I have to use an int to count through?
I'm sure there's a simpler way...

You can do this with Linq quite easily:
var newStringList = myStringList
.Select(s => s + "-")
.ToList();
If you really want to modify the existing list, you can use a classic for loop, for example:
for (var i = 0; i < myStringList.Count; i++)
{
myStringList[i] = myStringList[i] + "-";
}

Try this
List<string> listString = new List<string>() { "1","2","3"};
listString=listString.Select(x => x + "-").ToList();

Related

Visual Basic C# with Selenium variable in css selector

I am only a week or so into C#, but thanks to forums like this I am able to piece together a bunch of code and get a general understanding. However, I have a problem with using a variable I can't solve.
List<IWebElement> elementList = new List<IWebElement>();
elementList.AddRange(browser.FindElements(By.CssSelector("div[class^='CalendarDays-calendarDays-']>div:nth-child(3)>div>div[class^='CalendarEvent-event-']")));
int t = elementList.Count;
for (int i = 1; i <= t; i++)
{
var item + i = browser.FindElement(By.CssSelector("div[class^='CalendarDays-calendarDays-']>div:nth-child(3)>div>div:nth-child(i)>div>div[class^='CalendarEvent-title']")).GetAttribute("textContent");
}
Problems are "var item + i" and "div:nth-child(i)". The first is automatically creating sequential variables and the second trying to get the nth-child using the variable "i". I can't figure out how to format "i" in either instance.
Any help would be appreciated.
Working Code after edits:
List<IWebElement> elementList = new List<IWebElement>();
elementList.AddRange(browser.FindElements(By.CssSelector("div[class^='CalendarDays-calendarDays-']>div:nth-child(3)>div>div[class^='CalendarEvent-event-']")));
int t = elementList.Count;
List<String> listItems = new List<String>();
for (int i = 1; i <= t; i++)
{
String item = browser.FindElement(By.CssSelector("div[class^='CalendarDays-calendarDays-']>div:nth-child(3)>div>div:nth-child(i)>div>div[class^='CalendarEvent-title']")).GetAttribute("textContent");
listItems.Add(item);
}
Thanks,
Don
You should use a list to store the different items, you have to know the type of GetAttribute. I assume it is String :
List<String> listItems = new List<String>();
for (int i = 1; i <= t; i++)
{
String item = browser.FindElement(By.CssSelector("div[class^='CalendarDays-calendarDays-']>div:nth-child(3)>div>div:nth-child(i)>div>div[class^='CalendarEvent-title']")).GetAttribute("textContent");
listItems.Add(item);
}
then you can access the list items by index listItems[i]
For the second part of the question you have to concatenate the string with the i of the for loop like this:
browser.FindElement(By.CssSelector("div[class^='CalendarDays-calendarDays-']>div:nth-child(3)>div>div:nth-child("+i+")>div>div[class^='CalendarEvent-title']")).GetAttribute("textContent");
You can't do var item + i. Just use the same variable each time, it's inside the loop scope anyway.
To insert the i variable to the locator you can use string interpolation
var item = browser.FindElement(By.CssSelector($"div[class^='CalendarDays-calendarDays-']>div:nth-child(3)>div>div:nth-child({i})>div>div[class^='CalendarEvent-title']")).GetAttribute("textContent");

Convert Array List to Comma Separated String in C#

I'm using String.Join to attempt to turn an array list into a string that is comma separated, such as
xxx#xxx.com,yyy#xxx.com,zzz#xxx.com,www#xxx.com
I can't seem to get the syntax working.
Here's what I'm trying:
for (i = 0; i < xxx; i++)
{
MailingList = arrayList[i].ToString();
MailingList = string.Join(", ", MailingList.ToString());
Response.Write(MailingList.ToString());
}
Can you help me?
Thank you in advance-
Guessing from the name of your variable (arrayList), you've got List<string[]> or an equivalent type there.
The issue here is that you're calling ToString() on the array.
Try this instead:
for (i = 0; i < xxx; i++)
{
var array = arrayList[i];
MailingList = string.Join(", ", array);
Response.Write(MailingList);
}
EDIT: If arrayList is simply an ArrayList containing strings, you can just do
Response.Write(string.Join(", ", arrayList.OfType<string>()));
Personally I would avoid using nongeneric collections (such as ArrayList) if possible and use strongly-typed collections from System.Collections.Generic such as List<string>. For example, if you have a piece of code that depends on that all contents of the ArrayList are strings, it will suffer catastrophically if you accidentally add an item that's not a string.
EDIT 2: If your ArrayList actually contains System.Web.UI.WebControls.ListItems like you mentioned in your comment: arrayList.AddRange(ListBox.Items);, then you'll need to use this instead:
Response.Write(string.Join(", ", arrayList.OfType<ListItem>()));
The second parameter for String.Join needs to be an IEnumerable. Replace MailingList.ToString() with arrayList and it should work.
Initialization:
string result = string.Empty;
For value types:
if (arrayList != null) {
foreach(var entry in arrayList){
result += entry + ',';
}
}
For reference types:
if (arrayList != null) {
foreach(var entry in arrayList){
if(entry != null)
result += entry + ',';
}
}
And cleanup:
if(result == string.Empty)
result = null;
else
result = result.Substring(0, result.Length - 1);
most of the answers are already there, still posting a complete - working snippet
string[] emailListOne = { "xxx#xxx.com", "yyy#xxx.com", "zzz#xxx.com", "www#xxx.com" };
string[] emailListTwo = { "xxx#xxx1.com", "yyy#xxx1.com", "zzz#xxx1.com", "www#xxx1.com" };
string[] emailListThree = { "xxx#xxx2.com", "yyy#xxx2.com", "zzz#xxx2.com", "www#xxx.com" };
string[] emailListFour = { "xxx#xxx3.com", "yyy#xxx3.com", "zzz#xxx3.com", "www#xxx3.com" };
List<string[]> emailArrayList = new List<string[]>();
emailArrayList.Add(emailListOne);
emailArrayList.Add(emailListTwo);
emailArrayList.Add(emailListThree);
emailArrayList.Add(emailListFour);
StringBuilder csvList = new StringBuilder();
int i = 0;
foreach (var list in emailArrayList)
{
csvList.Append(string.Join(",", list));
if(i < emailArrayList.Count - 1)
csvList.Append(",");
i++;
}
Response.Write(csvList.ToString());

Need to add each number 0-x to end of line?

I'm making an app and I'm almost done. I just need to know how I can streamread a txt list and foreach line, add numbers 0-x (x will be the number the user puts in the textbox) and add it to a list. So basically, it would be like this
You import a list with 'dog' on one line, 'cat' on another, and 'fish' on the third. You type '5' into the textbox. the app puts all this into a list:
dog1
dog2
dog3
dog4
dog5
cat1
cat2
cat3
cat4
cat5
fish1
fish2
fish3
fish4
fish5
thanks!
The code below should work for you. I assume you can acquire the count value on your own.
var animals = File.ReadAllLines("yourFile.txt"); //new[] {"dog", "cat", "fish"};
var count = 5;
var merged =
from a in animals
from n in Enumerable.Range(1, count)
select a + n;
foreach (var m in merged)
Console.WriteLine(m); //act on each however you want
You can read a text file with File.ReadAllLines. This gives you an array you can iterate over with foreach.
In this foreach loop you can perform another loop from 1 to the number the user entered. int.Parse comes in handy for converting the string the user entered into a number C# can do something with. For the actual iteration you can use a for loop.
You can then add each item to a list.
There is a good example for reading each line in a filestream here: http://msdn.microsoft.com/en-us/library/e4y2dch9.aspx
private List<string> GetThings(string fileName, int count)
{
string[] lines = File.ReadAllLines(fileName);
List<string> result = new List<string>();
foreach (string item in lines)
{
for (int i = 1; i <= count; i++)
result.Add(item + i.ToString());
}
return result;
}
string[] inputList = File.ReadAllLines("yourFile.txt");
List<String> listOfThings = new List<String>();
foreach (string i in inputList)
{
for (int k = 0; k < 5; k++)
{
listOfThings.Add(i + " " + k.ToString());
}
}
then after that, you can print out the list like this:
foreach (string outp in listOfThings)
{
Console.WriteLine(outp);
}
output:
some value 0
some value 1
some value 2
some value 3
some value 4
some other value 0
some other value 1
some other value 2
some other value 3
some other value 4

Looping through x number of arrays

How do I loop through x number of arrays and visit all combinations of all cells in all of the arrays? The problem here is there can be x number of arrays of some items inside. For instance,
List<List<string>> _arrays = GetArrayInformation();
I want to compare all the string inside each array with all the other arrays and the strings inside of each array. Do I use while like
while(i < _arrays.Count)
Thanks for your answer. The answer seems simple but when you think about it is kind of tricky and hard.
Update:
Thanks for your answers. I can do this with a 3 arrays like
for(int i = 0; i < _arrays[0].Count; i++) {
for(int l = 0; l < _arrays[1].Count; l++) {
for(int m = 0; m < _arrays[2].Count; m++) {
string _hello = _arrays[0][i] + "|" + _arrays[1][l] + "|" + _arrays[2][m];
}
}
}
Because I have dynamic number of arrays, it gets tricky.
foreach(var array in _arrays)
{
foreach(var s in array)
{
foreach(var otherArray in _arrays)
{
if(otherArray == array) continue;
if(otherArray.Contains(s)) {} // not sure what you want to do
}
}
}
this will loop through every single string seeing if it is in any other array.... it's the straightforward approach, but not very efficient and will duplicate work.
There is no enough information is here
If you need to find elements that exists in few array You will use something like this:
var multipleWords = _arrays
.SelectMany(items => items.Distinct())
.GroupBy(item => item)
.Select(group => new {Item = group.Key, Count = group.Count()})
.Where(item => item.Count > 1)
.Select(item => item.Item)
.ToArray();
multipleWords will contain each word from the all these arrays that exists in two or more arrays
You could use a recursive search function.
public Search<T>(object o, string comparestring)
{
if(o is List<string>)
{
//Compare to your string
}
else
{
//Call this search function with the type of the object in the list.
//Will iterate through all of your strings recursively.
Type t = o.GetType().GetGenericArguments()[0];
foreach( object osub in (T)o)
Search<t>( ((t)o),comparestring)
}
}

comparing string and variable but failing based on contains

What I have going on is I have two files. Both files are delimited by '|'. If file 1 matches a line in file 2 I need to combine the lines. Here is the code:
string[] mathlines = File.ReadAllLines(#"C:\math.txt");
var addlines = File.ReadAllLines(#"K:\add.txt");
foreach (string ml in mathlines)
{
string[] parse = ml.Split('|');
if (addlines.Contains(parse[0]))
{
File.AppendAllText(#"C:\final.txt", parse[0]+"|"+parse[1]+"\n");
}
else
{
File.AppendAllText(#"C:\final.txt", ml + "\n");
}
}
I realize that the math part isn't setup yet, but I need to get the match part working.
Here is an example:
mathlines:
dart|504.91
GI|1782.06
Gcel|194.52
clay|437.35
grado|217.77
greGCR|14.82
rp|372.54
rp2|11.92
gsg|349.92
GSxil|4520.55
addlines:
Gimet|13768994304
GSxil|394735896576
Ho|4994967296
gen|485331304448
GSctal|23482733690
Obr|88899345920
As you can see mathlines contains GSxil and so does addlines but my if (addlines.Contains) never fines the variable in addlines. Any help is always loved! Thanks.
Sorry forgot to mention that I need it to match exactly on the comparison. Also i need to split out the variable on the correct line that matches. So I would need to split out the 394735896576 this example and then append the 394735896576.
addLines.Contains(parse[0]) is going to match on the entire string; you need to match based on part. There are more efficient solutions, but a O(n^2) option is to use LINQ Any():
if (addLines.Any(l => l.StartsWith(parse[0])))
{
...
You could load all lines from addlines.txt into a dictionary and then use that to find a match for each line in mathlines.txt. This method would be much faster than what you have currently.
string[] mathlines = File.ReadAllLines(#"C:\math.txt");
string[] addlines = File.ReadAllLines(#"K:\addlines.txt");
string[] finallines = new string[mathlines.Length];
var addlinesLookup = new Dictionary<string, string>();
for (int i = 0; i < addlines.Length; i++)
{
string[] parts = addlines[i].Split('|');
if (parts.Length == 2) // Will there ever be more than 2 parts?
{
addlinesLookup.Add(parts[0], parts[1]);
}
}
for (int i = 0; i < mathlines.Length; i++)
{
string[] parts = mathlines[i].Split('|');
if (parts.Length >= 1)
{
if (addlinesLookup.ContainsKey(parts[0]))
{
finallines[i] = mathlines[i] + "|" + addlinesLookup[parts[0]] + "\n";
}
{
finallines[i] = mathlines[i] + "\n";
}
}
}
File.AppendAllLines(#"C:\final.txt", finallines, Encoding.ASCII);

Categories