I have adapted some code that generates a random state value (below)
public static string GenRandomState()
{
List<string> lst = new List<string>();
randomState = string.Empty;
lst.Add("Alabama");
lst.Add("Alaska");
lst.Add("Arizona");
...
randomState = lst.OrderBy(xx => rnd.Next()).First();
return randomState;
} // End GenRandomState
I would like to remove the randomization and, instead, have the method call the states in the same order (Top to Bottom) each time the method is called.
So, what I'd like to see is this: each iteration, a state value (starting at the top) will be retrieved. The execution will continue until all the state values have been called. I think a Foreach loop would be appropriate but I am not sure how best to implement.
Because you are leaving the loop and only selecting one state each call I would not use a foreach loop and instead keep a index variable and use that to choose which index you are going to use.
First, I would move the creation of the list outside of the function so it is only done once.
public class StateInfo
{
static StateInfo()
{
lst.Add("Alabama");
lst.Add("Alaska");
lst.Add("Arizona");
...
}
static readonly List<string> _lst = new List<string>();
static readonly object _listLock = new object();
static int _nextIndex = 0;
public static string GetNextState()
{
int i = 0;
lock(_listLock)
{
i = _nextIndex;
_nextIndex = (_nextIndex + 1) % _lst.Count;
}
return _lst[i];
}
}
You can change the function to return an IEnumerable.
static void Main(string[] args)
{
foreach (var s in GetStates())
{
Console.WriteLine(s);
}
}
public static IEnumerable<string> GetStates()
{
var lst = new List<string>();
lst.Add("Alabama");
lst.Add("Alaska");
lst.Add("Arizona");
...
return lst;
}
Related
I am making console app using Array class that has username as object, this is member.cs
Class Member{
public string username;
public Member(){
}
public Member(string username){
username = username;
}
}
And this is my Collection.cs
Class Collection{
static Member[] members = new Member[100];
public void Adduser(){
console.writeLine("username?");
string user_input = console.ReadLine();
members = new Member[]{
new Member(user_input)
};
}
public Member[] get() {
return members;
}
}
but every time the Adduser() functions is called, it only stores one member and keeps updating to a new member, in here I am expecting to have 100 usernames at most.
How should I store multiple values in side the constructor or Array object?
Should I create a new array in member class to store multiple-member?
Even after I implemented index, I get nullexception error in side foreach
public void showMember()
{
var data = record.get();
foreach (var value in data)
{
Console.WriteLine(value.Username);
Console.WriteLine(value.Phonenum);
Console.WriteLine(value.Password);
Console.WriteLine(value.Borrowedmovie);
}
}
that's because you renew the array every time.this might help.
int index=0;
public void Adduser(){
console.writeLine("username?");
string user_input = console.ReadLine();
if(index<members.Length)
{
members[index]=new Member(user_input)
index++;
}
else console.writeLine("overflow");
}
}
also I think it's better if you use list instead of array
static List<Member> members = new List<Member>();
public void Adduser(){
console.writeLine("username?");
string user_input = console.ReadLine();
members.Add(new Member(user_input));
}
Instead of an array you should use an List object.
Class Collection{
static List<Member> members = new List<Member>();
public void Adduser(){
console.writeLine("username?");
string user_input = console.ReadLine();
members.Add(new Member(user_input));
}
}
Use index variable and update it everytime u add an item.
Class Collection{
static Member[] members = new Member[100];
int index = 0;
public void Adduser(){
console.writeLine("username?");
string user_input = console.ReadLine();
members[index] = new Member(user_input);
index++;
}
}
Since array is already instantiated with 100 elements, we can not check length of array to check whether elements exists or not.
Array.length will always give the max length of array since the memory is allocated for 100 elements.
But you can check whether last element exists or not and then you can add the new element.
Below code snippet can help you:
class Member
{
public string _username;
public Member()
{
}
public Member(string username)
{
_username = username;
}
}
class Collection
{
private Member[] members = new Member[100];
private int index = 0;
public void Adduser()
{
Console.WriteLine("username?");
string user_input = Console.ReadLine();
var lastElement = members[members.Length - 1];
if (lastElement != null)
{
Console.WriteLine("members array is already full");
return;
}
members[index] = new Member(user_input);
index++;
}
public void DisplayMembers()
{
foreach (var item in members)
{
if (item != null)
{
Console.WriteLine("UserName {0}", item._username);
}
}
}
}
Following is a code for testing the functionality:
static void Main(string[] args)
{
Collection collection = new Collection();
collection.Adduser();
collection.Adduser();
collection.Adduser();
collection.Adduser();
collection.Adduser();
collection.Adduser();
collection.DisplayMembers();
Console.WriteLine("Start second collection");
Collection collection2 = new Collection();
collection2.Adduser();
collection2.Adduser();
collection2.Adduser();
collection2.Adduser();
collection2.Adduser();
collection2.DisplayMembers();
Console.ReadLine();
}
This question already has answers here:
Help someone new to C# variables
(5 answers)
Closed 2 years ago.
In my current application while I have been able to implement the required logic that I need I am really stuck when trying to take off the content from the main method and using it from a different method .
My code is as below,
class Program
{
const string path = #"filePath";
static void Main(string[] args)
{
setUpValues();
}
private static void setUpValues()
{
var Content = JsonConvert.DeserializeObject<deploy>(File.ReadAllText(path));
List<Variable> variables = Content.Variables.ToList();
Scopes Scope = Content.ScopeValues;
string Version = null;
List<string> ListOfSelectedItems= new List<string>();
List<string> TempListOfSelectedItems = new List<string>();
List<string> Channels = new List<string>();
foreach (var item in variables)
{
if (item.Name.Equals("version"))
{
Version = item.Value;
}
if (item.Name.Equals("Selected"))
{
TempListOfSelectedItems.Add(item.Value);
}
}
Console.WriteLine("Version " + Version);
Console.WriteLine();
string SelectedItems= TempListOfSelectedItems[0];
ListOfSelectedItems = SelectedItems.Split(',').ToList();
Console.WriteLine();
Console.WriteLine("Selected Modules");
Console.WriteLine();
foreach (var item in ListOfSelectedItems)
{
Console.WriteLine(item);
}
foreach (var item in Scope.Channels)
{
Channels.Add(item.Name);
}
}
}
I want to be able to access the variable string Version , the List of ListOfSelectedItems and the List of channels from outside this method .. I want to use these in another as well . So how can I make these globally accessible ?
Would really appreciate your help on this as I have been stuck here
In order to use variables outside a method, you should declare them as fields of a class. Like this:
class Program
{
const string path = #"filePath";
static deploy Content;
static string Version;
static List<string> ListOfSelectedItems;
static List<string> TempListOfSelectedItems;
static List<string> Channels;
// and others
static void Main(string[] args)
{
setUpValues();
}
private static void setUpValues()
{
Content = JsonConvert.DeserializeObject<deploy>(File.ReadAllText(path));
List<Variable> variables = Content.Variables.ToList();
Scopes Scope = Content.ScopeValues;
Version = null;
ListOfSelectedItems = new List<string>();
TempListOfSelectedItems = new List<string>();
Channels = new List<string>();
foreach (var item in variables)
{
if (item.Name.Equals("version"))
{
Version = item.Value;
}
if (item.Name.Equals("Selected"))
{
TempListOfSelectedItems.Add(item.Value);
}
}
Console.WriteLine("Version " + Version);
Console.WriteLine();
string SelectedItems = TempListOfSelectedItems[0];
ListOfSelectedItems = SelectedItems.Split(',').ToList();
Console.WriteLine();
Console.WriteLine("Selected Modules");
Console.WriteLine();
foreach (var item in ListOfSelectedItems)
{
Console.WriteLine(item);
}
foreach (var item in Scope.Channels)
{
Channels.Add(item.Name);
}
}
}
You have to declare those fields as static because they are used in a static method. After the setUpValues finishes running, you can use those fields inside the Main method as well.
Also, this is not related to the question, but the general code convention in C# is to start methods' names with an uppercase letter (so SetUpValues instead of setUpValues) and to start the local variables' names with a lowercase letter (selectedItems instead of SelectedItems). Obviously, it's ultimately up to you how to name things and which code convention to use.
Create a class with properties that you want to access from other places. Instantiate this class in setUpValues and return this.
public class TestClass
{
public TestClass()
{
this.ListOfSelectedItems = new List<string>();
}
public string Version { get; set; }
public List<string> ListOfSelectedItems { get; set; }
}
And then modify your Main method as:
var myObj = setUpValues();
And then Modify setUpValues to return this:
private static TestClass setUpValues()
{
var Content = JsonConvert.DeserializeObject<deploy>(File.ReadAllText(path));
List<Variable> variables = Content.Variables.ToList();
Scopes Scope = Content.ScopeValues;
string Version = null;
List<string> ListOfSelectedItems = new List<string>();
List<string> TempListOfSelectedItems = new List<string>();
List<string> Channels = new List<string>();
foreach (var item in variables)
{
if (item.Name.Equals("version"))
{
Version = item.Value;
}
if (item.Name.Equals("Selected"))
{
TempListOfSelectedItems.Add(item.Value);
}
}
var retObj = new TestClass();
Console.WriteLine("Version " + Version);
Console.WriteLine();
retObj.Version = Version;
string SelectedItems = TempListOfSelectedItems[0];
ListOfSelectedItems = SelectedItems.Split(',').ToList();
Console.WriteLine();
Console.WriteLine("Selected Modules");
Console.WriteLine();
foreach (var item in ListOfSelectedItems)
{
Console.WriteLine(item);
retObj.ListOfSelectedItems.Add(item);
}
foreach (var item in Scope.Channels)
{
Channels.Add(item.Name);
}
return retObj;
}
I am coding an application for my study, but i'm stuck at this point. I made a class called 'Neighborhood'. This class has a string and an int. In my main code I give the class a value and put it in a list. I now want to loop through my list and get the int out of it (put it in a listbox, or do a calculation). How do I get the int out of the list?
class Wijk
{
private string wijken;
private int tijd;
public string Wijken
{
get { return wijken; }
set { wijken = value; }
}
public int Tijd
{
get { return tijd; }
set { tijd = value; }
}
}
Created the list and the instance of the class.
List<object> Uden = new List<object>();
Wijk Wijkeninput = new Wijk();
Now I value the string and int with a combobox and textbox.
private void wijkAanmaken()
{
Wijkeninput.Wijken = Convert.ToString(cbWijken);
Wijkeninput.Tijd = Convert.ToInt16(tbSnelheid.Text);
Uden.Add(Wijkeninput);
}
For this, instead of having an object list, you can have list containing class objects like
List<Wjik> Uden = new List<Wjik>();
then you can access int as follows:
foreach (Wjik obj in listProgram)
{
int tij = Convert.ToInt32(obj.tijd);
}
First the List can be declared like this:
List<Wijk> Uden = new List<Wijk>();
To iterate over it:
foreach(var item in Uden)
{
var myInt = item.Tijd;
var myString = item.Wijken;
//here do whatever you want with the values
}
I would like to create an array of objects. Each object has it's own int array.
For each object I assign values to it's array ONLY with keys given by myself (example: li[i].V[10] = 1; li[i].V[50] = 10; )
Can someone tell me how to do that? Can I do that without using Lists?
The second case is analogical to first. I would like to know how to assign values of object's List
using setter.
I tried to do that by myself. Unfortunately My code crashed cuz I don't know how to set the dimension of V and Word:
class CFiles
{
//private int[] v=new int[5];//dont want to specify the dimention of array here
private int[] v;//vector of file
private List<string> words;
public CFiles()
{
words = Words;
v = new int[50];
v = V;
}
public int[] V { get; set; }
public List<string> Words { get; set; }
}
class Program
{
static void Main(string[] args)
{
CFiles[] li = new CFiles[2];
for(int i=0;i<li.Length;i++)
{
li[i]=new CFiles();
li[i].V[10] = 1;
li[i].V[50] = 10;
li[i].V[50] = 15;
li[i].Words.Add("a");
li[i].Words.Add("ab");
li[i].Words.Add("abc");
}
for (int i = 0; i < li.Length; i++)
{
for(int j=0;j<li[i].V.Length;j++)
{
Console.WriteLine(li[i].V[j]);
}
}
Console.WriteLine();
}
}
Your constructor isn't right and your properties aren't quite right. You might want something more like this:
class CFiles
{
//private int[] v=new int[5];//dont want to specify the dimention of array here
private int[] v;
public int[] V { get { return v; } set { v = value; } }
private List<string> words;
public List<string> Words { get { return words; } set { words = value; } }
public CFiles()
{
words = new List<string>();
v = new int[51]; //needs to be 51 if you are going to assign to index 50 below
}
}
Other than those issues, your code seems to do what you want. You have an array of objects where each object has its own int array (in addition to a string of strings).
Is that not what you want?
I have two lists. The types of both lists inherit from the same base type. I want to iterate through them and do operations which only use functionality of the base class without having two basically identical foreach loops one after the other.
I can't copy the lists to another list or something of the sort, as I need to use the lists in their original form separately after the operation is complete.
Is there a way to do this without writing a function?
class Program
{
static void Main(string[] args)
{
// I have two lists of inherited classes
List<Babby1> list1 = returnBabby1();
List<Babby2> list2 = returnBabby2();
// I want to iterate through both, and do the same thing, which is a part
// of the base class functionality.
// Basically I want this to be a single foreach loop.
foreach (Babby1 item in list1)
item.var = 50;
foreach (Babby2 item in list2)
item.var = 50;
// I have to send them as separate lists, the type being the original (inherited) class
sendBabby1(list1);
sendBabby2(list2);
}
static void sendBabby1(List<Babby1> list)
{
}
static void sendBabby2(List<Babby2> list)
{
}
static List<Babby1> returnBabby1()
{
return new List<Babby1>();
}
static List<Babby2> returnBabby2()
{
return new List<Babby2>();
}
}
class Base
{
public int var;
}
class Babby1 : Base
{
public int var1;
}
class Babby2 : Base
{
public int var2;
}
This should do the trick...
foreach (var item in list1.Concat<Base>(list2))
{
// Do your thing
}
EDIT: I changed Union to Concat as I think that it's probably more appropriate.
Just use the base class, like this:
List<Babby> list = new List<Base>();
list.AddRange(returnBabby1());
list.AddRange(returnBabby2());
foreach (Base item in list)
item.var = 50;
sendBabby1(list.OfType<Babby1>().ToList());
sendBabby2(list.OfType<Babby2>().ToList());
(This of course assume you have the variable you set declared in the base class)
You can use the covariance of IEnumerable<T> in order to achieve this, if you plan to simply iterate the lists and not add items or perform other operations on the list:
static SendBaby(IEnumerable<Base> list)
{
...
}
...
SendBaby(list1)
SendBaby(list2)
You can use a for loop, using Count instead. (If comparisons do consume additional CPU cycles.)
for(int i=0;i<baby1.Count||i<baby2.Count;i++)
{
if(baby1.Count<i)
baby1[i].field = 50;
if(baby2.Count<i)
baby2[i].field = 50;
}
This does it pretty well :
var babies1 = new List<Baby1>(5);
for (int i = 0; i < 5; i++)
{
babies1.Add(new Baby1 { Name = "Babies1 " + i, Var1 = 1});
}
var babies2 = new List<Baby2>(5);
for (int i = 0; i < 5; i++)
{
babies2.Add(new Baby2 { Name = "Babies2 " + i });
}
foreach (Baby b in babies1.Union<Baby>(babies2))
{
b.Var1 = 50;
}
foreach (var baby2 in babies2)
{
Console.WriteLine(baby2.Var1);
}
foreach (var baby1 in babies1)
{
Console.WriteLine(baby1.Var1);
}