I am trying to pass a varying amount of strings into a List and than manipulate these strings.
I am attempting something like this but I think I am doing it wrong:
public static void ActivateStateFilter(List<string> lStatelist)
{
for (int index = 0; index < lStatelist.Count; index++) // Loop with for.
{
lStatelist.Add(lStatelist[index]); //Add strings to the list
}
}
This is how I attempt to pass values:
ActivateStateFilter(new List<string> {"Active", "Inactive"});
Thanks in advance!
You are adding the existing items how new item in the sended list.
Your code duplicate lStatelist with their existing items.
What are you really trying to do?
if you are trying to insert your string on specific index use this:
lStatelist.Insert(index, newstring);
Your code will throw an OutOfmemoryException, because you create an infinite loop.
You are adding the items of a list to the list containing the items… and you are doing this for every item in the list…which will create an infinite loop.
I think you are looking for something like this:
public class Program
{
private static readonly List<String> _lStateList = new List<String>();
static void Main( String[] args )
{
ActivateStateFilter( new List<String> { "1", "2" } );
}
private static void ActivateStateFilter( IEnumerable<String> values )
{
_lStateList.AddRange( values );
}
}
This code will add a range of stirng values to _lStateList
Related
I have this variable:
public static List<Phrase> viewablePhrases;
I would like to see the contents logged in the console like this:
Console.WriteLine(App.viewablePhrases)
but this doesn't show me the contents.
Is there a way I can see the contents in my Console?
You're trying to display the list, not the values of objects that you add to your list:
You should output the string values that cointains your Phrase object:
public static List<Phrase> viewablePhrases
{
new Phrase(/* your constructor */)
// other your Phrase objects
};
for(int i = 0; i < viewablePhrases.Count; i++)
{
Console.WriteLine(viewablePhrases[i].Value); // or other property instad of "Value"
}
You have to write out each item in the list, e.g.
foreach(var phrase in viewablePhrases)
{
Console.WriteLine(phrase.ToString());
}
This assumes that your Phrase class has a suitable override of ToString() that will return a readable string.
So I am working on this assignment, i'm sure you've seen it around.
It's basically a list witha bunch of arrays in it and this is what I did.
I declared this at the top of my class
static List<string[]> logBook = new List<string[]>();
static string[] post = new string[2];
And then I created a function / method that takes a user unput and adds it as a entry.
private static void addToArray()
{
Console.WriteLine("Title: ");
DateTime dt = DateTime.Now;
string userInput = dt + " " + Console.ReadLine();
Console.WriteLine("Message: ");
string userInputt = "\n\t\t" + Console.ReadLine();
post = new string[2];
post[0] = userInput;
post[1] = userInputt;
logBook.Add(post);
}
Now what I need to do is to create a function that searches for an entry and then I should be able to edit / remove it if I want to and this is what I was thinking of doing, somethign along these lines.
private static void searchArray()
{
post.Where(x => x.Contains("someString"));
for(int i = 0; i < logBook.Length; i++)
{
//And then use something here to get the index value of what I found with the .Contains method.
}
}
Now, i'm having an issue with the search function, I have no idea how tos tructure it? Is my way of thinking even correct here?
How would I properly search for an item and get the index value with it?
I think that first of all you should change your used datastructure, so you would end up with something like this:
static Dictionary<string, Tuple<string, string>> logBook = new Dictionary<string, Tuple<string, string>> ();
private static void addToArray()
{
var post = new Tuple<string, string>(userInput, userInputt);
logBook.Add(userInput, post);
logBook.Add(userInputt, post);
}
Then you can easilly search in O(1) time:
private static void search()
{
var key = "your key here";
if(logBook.ContainsKey(key))
{
var post = logBook[key]
// edit here
post.Item1 = ....
post.Item2 = ....
}
}
This solution doesn't handle duplicate input, modify properly if needed.
create a condition where (ex.) then makes removing and else makes adjusting. Adjusting can be made by searching,copying, removing the original, editing the copy and insert the later.
Hello need some assistance with this issue. Hopefully i can describe it well.
I have a parser that goes though a document and find sessionID's, strips some tags from them and places them into a list.
while ((line = sr.ReadLine()) != null)
{
Match sID = sessionId.Match(line);
if (sID.Success)
{
String sIDString;
String sid = sID.ToString();
sIDString = Regex.Replace(sid, "<[^>]+>", string.Empty);
sessionIDList.Add(sIDString);
}
}
Then I go thought list and get the distinctSessionID's.
List<String> distinctSessionID = sessionIDList.Distinct().ToList();
Now I need to go thought he document again and add the lines that match the sessionID and add them to the list. This is the part that I am having issue with.
Do I need to create a 2d list so I can add the matching log lines to the corresponding sessionids.
I was looking at this but cannot seem to figure out a way that I could copy over my Distinct list then add the Lines I need into the new array.
From what I can test it looks like this would add the value into the masterlist
List<List<string>> masterLists = new List<List<string>>();
Foreach (string value in distinctSessionID)
{
masterLists[0].Add(value);
}
How do I add Lines I need to the corresponding Masterlist. Say masterList[0].Add value is 1, how do i add the lines to 1?
masterList[0][0].add(myLInes);
Basically i want
Sessionid1
-------> related log line
-------> Related log line
SessionID2
-------> related log line
-------> related log line.
So on and so forth. I have the parsing all working, it's just getting the values into a 2nd string list is the issue.
Thanks,
What you can do is, simple create a class with public properties, and make list of that custom class.
public class Session
{
public int SessionId{get;set;}
public List<string> SessionLog{get;set;}
}
List<Session> objList = new List<Session>();
var session1 = new Session();
session1.SessionId = 1;
session1.SessionLog.Add("description lline1");
objList.Add(session1);
Here is one way to do it:
public class MultiDimDictList: Dictionary<string, List<int>> { }
MultiDimDictList myDictList = new MultiDimDictList ();
Foreach (string value in distinctSessionID)
{
myDictList.Add(value, new List<int>());
for(int j=0; j < lengthofLines; j++)
{
myDictList[value].Add(myLine);
}
}
You would need to replace lengthofLines with a number to indicate how many iterations of lines you have.
See Charles Bretana's answer here
I need to insert a string (from one window(QueryBuilder)) into an array(of another window(Main)).
In the Main i have a method as
public void DisplayCalcQuery(string argFromQueryBuilder)
{
int itemsInUserBuiltQueries = UserBuiltQueries.Count();
UserBuiltQueries[itemsInUserBuiltQueries] = argFromQueryBuilder.ToString();
//displayng the user built query(queries) on the stack panel meant to display it.
foreach (string query in UserBuiltQueries)
{
CheckBox checkQueries = new CheckBox() { Content = query };
stackPanel1.Children.Add(checkQueries);
checkboxes.Add(checkQueries);
}
}
Where UserBuiltQueries is declared as
string[] UserBuiltQueries;
However when from the other window i do
backscreen.DisplayCalcQuery(ttextBox1.Text.ToString()); //where backscreen is the Main
The argument is passed well but i get an error as
{"Value cannot be null.\r\nParameter name: source"}
What did I do wrong ?
These lines are wrong
int itemsInUserBuiltQueries = UserBuiltQueries.Count();
UserBuiltQueries[itemsInUserBuiltQueries] = argFromQueryBuilder.ToString();
Arrays start at index zero and end at index (Count - 1), so, if UserBuiltQueries.Count() returns 10 you could use indexes from 0 to 9. Essentially, using index 10, you are adding a new string outside the end of the array.
However, if your requirements force you to expand the array, it is better and more easy to code if you use a List<string> instead. Adding new elements will be a lot more easier and you could still use the List as an Array for common tasks.
List<string> UserBuiltQueries = new List<string>();
.....
public void DisplayCalcQuery(string argFromQueryBuilder)
{
UserBuiltQueries.Add(argFromQueryBuilder);
//displayng the user built query(queries) on the stack panel meant to display it.
foreach (string query in UserBuiltQueries)
{
CheckBox checkQueries = new CheckBox() { Content = query };
stackPanel1.Children.Add(checkQueries);
checkboxes.Add(checkQueries);
}
}
By the way, you should stop to unnecessarily convert a string to a string. You pass a ttextBox1.Text.ToString() but ttextBox1.Text is already a string. Inside the method the parameter argFromQueryBuilder is already a string and there is no need to convert to a string
Instead of using string[] for UserBuildQueries, use List. When you need it as an array, you can simply say: UserBuildQueries.ToArry()
Rewrite the function to
public void DisplayCalcQuery(string argFromQueryBuilder)
{
UserBuiltQueries.Add(argFromQueryBuilder.ToString());
//displayng the user built query(queries) on the stack panel meant to display it.
foreach (string query in UserBuiltQueries)
{
CheckBox checkQueries = new CheckBox() { Content = query };
stackPanel1.Children.Add(checkQueries);
checkboxes.Add(checkQueries);
}
}
In c# but I think in all programming language indexis start from 0:
so if an array has length or count =1 the index is 0 array[0], array.lenght==1
int itemsInUserBuiltQueries = UserBuiltQueries.Count()-1;
UserBuiltQueries[itemsInUserBuiltQueries] = argFromQueryBuilder.ToString();
And double check that your array is initialized before using it!
How can I dissect or retrieve string values?
Here's the sample code that I'm working on now:
private void SplitStrings()
{
List<string> listvalues = new List<string>();
listvalues = (List<string>)Session["mylist"];
string[] strvalues = listvalues.ToArray();
for (int x = 0; x < strvalues.Length; x++)
{
}
}
Now that I'am able to retrieve list values in my session. How can I separately get the values of each list using foreach or for statement?
What I want to happen is to programmatically split the values of the strings depending on how many is in the list.
If you have a list of string values, you can do the following:
private void SplitStrings()
{
List<string> listValues = (List<string>) Session["mylist"];
// always check session values for null
if(listValues != null)
{
// go through each list item
foreach(string stringElement in listValues)
{
// do something with variable 'stringElement'
System.Console.WriteLine(stringElement);
}
}
}
Note that I test the result of casting the session and that I don't create a new list first-off, which is not necessary. Also note that I don't convert to an array, simply because looping a list is actually easier, or just as easy, as looping an array.
Note that you named your method SplitStrings, but we're not splitting anything. Did you mean to split something like "one;two;three;four" in a four-element list, based on the separator character?
I'm not sure what you're trying to obtain in this code, I don't know why you're converting your List to an Array.
You can loop through your listValues collection with a foreach block:
foreach(string value in listValues)
{
//do something with value, I.e.
Response.Write(value);
}
I don't know what's in the strings but you can start by simplifying. There is no point allocating a new List if you're going to overwrite it immediately.
private void SplitStrings()
{
List<string> list = (List<string>)Session["mylist"];
foreach(string value in list)
{
}
}
List listvalues = (List)Session["mylist"];
foreach (string s in listvalues)
{
//do what you want with s here
}