Loop object creation - c#

I need to have my second nested for loop send the array values to class friends.
I do not know how I would go about this?
Unless I missed something in the class?
namespace List
{
class Program
{
public const int ARRAYSIZE = 5;
static void Main()
{
string[] relSend = { "Enter name", "enter phone number", "enter 2 didigt month dob", "enter 2 digit day dob", "enter 2 digit dob year" };
string[] In = new string[5];
string[] answer = new string[10];
for (int x = 0; x <= 8; x++)
{
for (int i = 0; i < relSend.Length; i++)
{
WriteLine("{0}", relSend[i]);
In[i] = Console.ReadLine();
}
for (int i = 0; i < In.Length; i++)
{
}
}
}
}
}
public class Friends
{
public string Name { get; set; }
public int Phone { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}

I guess you mean you want to create an object out of the information collected, that is no problem:
List<Friend> friends = new List<Friend>();
for (int x = 0; x <= 8; x++)
{
for (int i = 0; i < relSend.Length; i++)
{
WriteLine("{0}", relSend[i]);
In[i] = Console.ReadLine();
}
friends.Add( new Friend() { Name = In[0]
, Phone = int.Parse(In[1])
, Month = int.Parse(In[2])
, Day = int.Parse(In[3])
, Year = int.Parse(In[4])
}
);
}
Make sure to validate the input before creating the object! Also, I would suggest to use string for a phone number since you would lose the 0 that is the usual prefix. Month, Day and Year might be combined in a single DateTime.

Tell me if you need any explanations:
namespace List
{
class Program
{
//Create a dictionary to find out each question is realated to which property.
private static Dictionary<string, string> questions = new Dictionary<string, string>();
static void Main()
{
questions.Add("Enter name", "Name");
questions.Add("enter phone number", "Phone");
questions.Add("enter 2 didigt month dob", "Month");
questions.Add("enter 2 digit day dob", "Day");
questions.Add("enter 2 digit dob year", "Year");
//Create list of friends
List<Friends> friendsList = new List<Friends>();
for (int x = 0; x <= 8; x++)
{
Friends f = new Friends();
foreach (string q in questions.Keys)
{
Console.WriteLine("{0}", q);
//Find property using Sytem.Reflection
System.Reflection.PropertyInfo property = f.GetType().GetProperty(questions[q]);
//Set value of found property
property.SetValue(f, Convert.ChangeType(Console.ReadLine(), property.PropertyType), null);
}
//Add a friend to list
friendsList.Add(f);
}
}
}
}
public class Friends
{
public string Name { get; set; }
public int Phone { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}

Related

For loop takes the the max count

private List<SurveyDetail> GetSurveyDetails()
{
List<SurveyDetail> surveyDetails = new List<SurveyDetail>();
SurveyDetail detail = new SurveyDetail();
int cid = 0;
for (int i = 1; i < 3; i++)
{
detail.choiceId = "1";
detail.choiceDesc = "tesT";
detail.questionId = i.ToString();
surveyDetails.Add(detail);
}
return surveyDetails;
}
public class SurveyDetail
{
public string questionId { get; set; }
public string choiceId { get; set; }
public string choiceDesc { get; set; }
}
when I run the code it question Id always gives me the last number of i that was run for example, in this case, it gives me 2. It gives me 2 on both counts.
Where I want the questionid to be 1 in the first count and 2 in the second.
You should move SurveyDetail initialization into the for body
private List<SurveyDetail> GetSurveyDetails()
{
List<SurveyDetail> surveyDetails = new List<SurveyDetail>();
int cid = 0;
for (int i = 1; i < 3; i++)
{
SurveyDetail detail = new SurveyDetail();//<==NOTE THIS
detail.choiceId = "1";
detail.choiceDesc = "tesT";
detail.questionId = i.ToString();
surveyDetails.Add(detail);
}
return surveyDetails;
}
Incase you want to use : LINQ
var result = Enumerable.Range(1, 3).Select(detail => new SurveyDetail
{
choiceId = "1",
questionId = detail.ToString(),
choiceDesc = "testT",
});

C# increment when creating new object via Array

So I am adding/creating objects within Console class via an array:
string[] console_available = { "Yes", "Yes", "Yes", "Yes", "Yes" };
for (int i = 0; i < console_available .Length; i++)
{
Classes.Console console = new Classes.Console(console_available[i]);
}
In the class itself I have int console_id which I want to increment but for some reason it only increments it once with the below constructor:
public int ConsoleID { get; set; } = 0;
public string Available { get; set; }
public Console(string available)
{
ConsoleID++;
this.Available = available;
}
So in essence its all "1 Yes" where I need it to be "1 Yes", "2 Yes", "3 Yes".
I don't really want to go down the route of having multiple lines of code to create the objects, e.g.:
Classes.Console console = new Classes.Console("Yes");
Classes.Console console2 = new Classes.Console("Yes");
Classes.Console console3 = new Classes.Console("Yes");
You'll need a static variable that you increment and store in a member variable:
private static int _ID = 1;
public int ConsoleID { get; set; };
public string Available { get; set; }
public Console(string available)
{
ConsoleID = _ID++;
this.Available = available;
}

C# cannot convert Int to Double

I get the error converting Int to Double, my next line Average[y] = Average[y] + Students[i].Marks; is not working either. So how can convert int[] to double[]?
public static double[] Averages(StudentMarks[] Students, int amount, string[] DifferentGroups, int GroupAmount, out double[] Average)
{
Average = new double[Max];
int y = 0;
int CountGroups = 0;
//int sum = 0;
for (int i = 0; i < amount; i++)
{
if (Students[i].Group == DifferentGroups[y])
{
Convert.ToDouble(Students[i].Marks);
//Average[y] = Average[y] + Students[i].Marks;
}
}
return Average;
}
The main:
static void Main(string[] args)
{
int amount;
StudentMarks[] Students;
string[] DifferentGroups;
int GroupAmount;
double[] Average;
ReadData(out Students, out amount);
DifferentGroups = FindDifferentGroups(Students, amount, out DifferentGroups, out GroupAmount);
Average = Averages(Students, amount, DifferentGroups, GroupAmount, out Average);
Class:
public const int Max = 50;
public string Surname { get; set; }
public string Name { get; set; }
public string Group { get; set; }
public int AmountOfMarks { get; set; }
public int[] Marks { get; set; }
So Student[i].Marks is Array.
Convert.ToDouble returns a double - it does not make an integer property or variable a double.
I think you want:
if (Students[i].Group == DifferentGroups[y])
{
double mark = Convert.ToDouble(Students[i].Marks);
Average[y] = Average[y] + mark;
}
or just:
if (Students[i].Group == DifferentGroups[y])
{
Average[y] = Average[y] + Convert.ToDouble(Students[i].Marks);
}
All Convert.ToXXX functions return the new value. Therefore, you should be expecting that and assigning the return value to a local variable.
Something like:
double YourMark = Convert.ToDouble(Students[i].Marks);
So how can convert int[] to double[]?
By programming. You write code to do it.
var d = new double[Students[i].Marks.Length];
for (int j = 0; j < Students[i].Marks.Length; ++j)
{
d[j] = Convert.ToDouble(Students[i].Marks[j]);
}
Or use LINQ:
var d = Students[i].Marks.Select(n => Convert.ToDouble(n)).ToArray();
Next time a method call won't compile or doesn't work the way you hoped it might, a good first step would be to check the documentation.

list class property in a class c# assign value

class Program
{
static void Main(string[] args)
{
Posting onjPosting = null;
List<Posting> objList = null;
for (int i = 0; i < 100; i++)
{
onjPosting = new Posting();
onjPosting.Key1 = i;
for (int j = 0; j < 5; i++)
{
Choice objChoice = new Choice();
objChoice.ID = i;
objChoice.VAL = j;
onjPosting.GetPostingChoice.Add(objChoice); // GETTING ERROR [ Object reference not set to an instance of an object. ]
}
objList.Add(onjPosting);
}
}
}
public class Choice
{
public int ID { get; set; }
public int VAL { get; set; }
}
public class Posting
{
public int Key1 { get; set; }
public List<Choice> GetPostingChoice { get; set; }
}
While looping through and assigning the value I am getting error . How to solve this ? Please help me out .
My requirement is one parent class (Posting) , can contain number of data List .
Thanks in advance .
You never allocate the GetPostingChoice list so of course it is null.
You could do it in the constructor:
public class Posting
{
public Posting()
{
GetPostingChoice = new List<Choice>();
}
public int Key1 { get; set; }
public List<Choice> GetPostingChoice { get; set; }
}
Add a public constructor on your Posting class:
public class Posting
{
public int Key1 { get; set; }
public List<Choice> GetPostingChoice { get; set; }
public Posting()
{
GetPostingChoice = new List<Choice>();
}
}
You also have other errors:
You do not initialize objList, so you cannot add in there.
List<Posting> objList = null;
So you will get another Null Reference when you get to:
List<Posting> objList = null;
In your second loop you increase i instead of j so it will never end.
for (int j = 0; j < 5; i++)
This is how it should look:
Posting onjPosting = null;
List<Posting> objList = new List<Posting>();
for (int i = 0; i < 1; i++)
{
onjPosting = new Posting();
onjPosting.Key1 = i;
for (int j = 0; j < 5; j++)
{
Choice objChoice = new Choice();
objChoice.ID = i;
objChoice.VAL = j;
onjPosting.GetPostingChoice.Add(objChoice); // GETTING ERROR [ Object reference not set to an instance of an object. ]
}
objList.Add(onjPosting);
}
Since you ask for another approach, and this is just one of the many ways you could do it, have a look at this:
List<Posting> objList = new List<Posting>();
Enumerable.Range(0,100)
.Select
(
(x,i)=>new Posting
{
Key1 = i,
GetPostingChoice = Enumerable.Range(0,5).Select((p,j)=>new Choice{ID = i,VAL = j}).ToList()
}
);

Combining numbers and names collections

I have 2 List collections. One contains numbers, the other names. There are twice as many numbers as names(always). I want to take the first name from the collection and the first two numbers from the other collection then put them together in a 3rd user collection of (VentriloUser). Then the second name needs to be matched with the 3rd and 4th numbers and so on.
I was thinking something with a for or foreach loop, but I can't wrap my head around it right now.
public class VentriloUser
{
public VentriloUser(string name, int seconds, int ping)
{
Name = name; Seconds = seconds; Ping = ping;
}
public string Name { get; set; }
public int Ping { get; set; }
public int Seconds { get; set; }
}
public class Ventrilo
{
public Ventrilo(string statusurl)
{
StatusURL = statusurl;
}
public string StatusURL { get; set; }
public string HTML { get; set; }
public List<VentriloUser> Users { get; set; }
private Regex findNumbers = new Regex("\\<td width=\"10%\" bgcolor=\"#\\w{6}\"\\>\\<font color=\"#000000\">\\<div style=\"overflow:hidden;text-overflow:ellipsis\"\\>-?\\d+\\<");
private Regex findNames = new Regex("\\<td width=\"20%\" bgcolor=\"#\\w{6}\"\\>\\<font color=\"#000000\">\\<div style=\"overflow:hidden;text-overflow:ellipsis\"\\>\\b\\w+\\<");
private WebClient wClient = new WebClient();
public void DownloadHTML()
{
HTML = wClient.DownloadString(StatusURL);
}
public List<int> GetNumbers()
{
var rawnumbers = findNumbers.Matches(HTML);
var numbers = new List<int>();
foreach (var rawnumber in rawnumbers)
{
var match = Regex.Match(rawnumber.ToString(), "\\>\\-?\\d+\\<");
string number = Regex.Replace(match.ToString(), "\\<|\\>", "");
numbers.Add(Convert.ToInt32(number));
}
return numbers;
}
public List<string> GetNames()
{
var rawnames = findNames.Matches(HTML);
var names = new List<string>();
foreach (var rawname in rawnames)
{
var match = Regex.Match(rawname.ToString(), "\\>\\w+<");
string name = Regex.Replace(match.ToString(), "\\<|\\>", "");
names.Add(name);
}
return names;
}
public List<VentriloUser> GenerateUsers()
{
var numbers = GetNumbers();
var names = GetNames();
var users = new List<VentriloUser>();
}
}
I am a hobbyist, but hope to pursue a career one day. Any help is much appreciated. Thank you for your time.
Using LINQ:
var users = names.Select((name,idx) => new VentriloUser(name, numbers[idx*2], numbers[idx*2+1]))
.ToList();
Using loops:
var users = new List<VentriloUser>();
for (int i = 0; i < names.Count; i++)
{
var name = names[i];
int j = i * 2;
if (j >= numbers.Count - 1)
break; // to be safe...
users.Add(new VentriloUser(name, numbers[j], numbers[j + 1]));
}

Categories