I have a problem about populating list<> elements. I tried to set a value to first element of list<> object but it didn't work. Here is my two classes:
CLASS
class hotel
{
public List<room> rooms = new List<room>();
}
class room
{
public string roomName;
}
Form1.cs
private void Form1_Load(object sender, EventArgs e)
{
string word = "example";
hotel[] h = new hotel[3];
for (int i = 0; i < h.Length; i++)
{
h[i] = new hotel();
h[i].rooms[i].roomName = word;//It gives "Index out of range exception" error.
}
}
You're getting an error because, while you have created a new hotel, you haven't added any rooms to it. Your code would have to do something like the following:
for (int i = 0; i < h.Length; i++)
{
h[i] = new hotel();
h[i].rooms.Add(new room { roomName = word });
}
If you want to add multiple rooms, you would either need to call Add multiple times or do so inside of an inner loop:
for (int i = 0; i < h.Length; i++)
{
h[i] = new hotel();
// Add 10 rooms
for (int a = 0; a < 10; a++)
{
h[i].rooms.Add(new room { roomName = word });
}
}
You have not added a room to the hotel:
h[i] = new hotel();
var room = new room();
room.roomName = word;
h[i].rooms.Add(room);
It may be easier to have a shortcut method in your class:
public class Hotel
{
public Hotel()
{
Rooms = new List<Room>();
}
public List<Room> Rooms { get; private set; }
public string Name { get; private set; }
public Hotel WithName(string name)
{
Name = name;
return this;
}
public Hotel AddRoom(string name)
{
Rooms.Add(new Room { Name = name });
return this;
}
}
public class Room
{
public string Name { get; set; }
}
Returning the Hotel object itself will allow method chaining on the same object to make the operations read fluently.
Demo:
var hotels = new List<Hotel>();
var hiltonHotel = new Hotel()
.WithName("Hilton")
.AddRoom("104")
.AddRoom("105");
hotels.Add(hiltonHotel);
Demo 2:
var hotelNames = new List<string> { "Hilton", "Sheraton", "Atlanta" };
var hotels = new List<Hotel>();
foreach(var hotelName in hotelNames)
{
var hotel = new Hotel()
.WithName(hotelName);
hotels.Add(hotel);
}
Demo 2 with LINQ:
var hotelNames = new List<string> { "Hilton", "Sheraton", "Atlanta" };
var hotels = hotelNames.Select(h => new Hotel().WithName(h)).ToList();
Use, You need to add room to hotel
h[i].rooms.Add(new room {roomName = word});
Instead of
h[i].rooms[i].roomName = word;
Related
I want to display multiple contents of country code in dropdown list in asp.net like this
Can I do it with bounding the data in dropdown list. I only display country codes with bounding data. Here is the code
public static class Countries
{
public static ISO3166Country[] getCollection()
{
return new ISO3166Country[] {
new ISO3166Country("Afghanistan", "+93"),
...
new ISO3166Country("Zimbabwe", "+263" )
};
}
public static List<string> getCountryList()
{
ISO3166Country[] array = getCollection();
List<string> countries = new List<string>();
for (int i = 0; i < array.Length; i++)
{
countries.Add(array[i].countryName);
}
return countries;
}
public static List<string> getCountryCodeList()
{
ISO3166Country[] array = getCollection();
List<string> countryCodes = new List<string>();
for (int i = 0; i < array.Length; i++)
{
countryCodes.Add(array[i].countryCode);
}
return countryCodes;
}
}
public class ISO3166Country
{
public ISO3166Country(string countryName, string dialCodes)
{
this.countryName = countryName;
countryCode = dialCodes;
}
public string countryName { get; private set; }
public string countryCode { get; private set; }
}
And bound data in page load
ddlPhoneCode.DataSource = Countries.getCollection();
ddlPhoneCode.DataBind();
I am also using bootstrap can I do this with bootstrap? any build in solution or have you already done this please give me the code.
may i know how to show sum of the child in parent in c# dataTreeListView
i have shared a screen shot
i wish to know how to show 5000 in person A which is sum of child table and the parent table can any one please help me
i want to do this on c# object listview
what i done to get above tree is
on form load i wrote this code
List<Class1> list = new List<Class1>();
list = Class1.GetList();
this.dataTreeListView2.ParentKeyAspectName = "ParentId";
this.dataTreeListView2.RootKeyValueString = "1";
BrightIdeasSoftware.OLVColumn col = new BrightIdeasSoftware.OLVColumn();
col.Width = 10;
dataTreeListView2.DataSource = list;
foreach (ColumnHeader column in this.dataTreeListView2.Columns)
{
column.Width = 100 + 100+ this.dataTreeListView2.SmallImageSize.Width;
}
this.dataTreeListView2.Columns.RemoveByKey("Id");
this.dataTreeListView2.Columns.RemoveByKey("ParentId");
and
class1.cs file has
namespace bbcon_accout_software
{
class Class1
{
/*public string Name { get; set;}
public Double Value { get; set; }
public List<Double> Children {get; set;}*/
protected string xName;
protected string xId;
protected string xParentId;
protected decimal xcredit;
protected decimal xdebit;
public Class1()
{
//Name = name;
//Value = value;
//Children = new List<Double>();
//Children.Add(2);
//Children.Add(3);
this.xName = "";
this.xId = "";
this.xParentId = "";
this.xcredit = 0.0M;
this.xdebit = 0.0M;
}
public String Name1
{
get { return this.xName; }
set { this.xName = value; }
}
public String Id
{
get { return this.xId; }
set { this.xId = value; }
}
public String ParentId
{
get { return this.xParentId; }
set { this.xParentId = value; }
}
public Decimal Credit
{
get { return this.xcredit; }
set { this.xcredit = value; }
}
public Decimal Debit
{
get { return this.xdebit; }
set { this.xdebit = value; }
}
public static List<Class1> GetList()
{
List<Class1> oList = new List<Class1>();
Class1 oClass4 = new Class1();
oClass4.Name1 = "Person A";
oClass4.Id = "xyz";
oClass4.ParentId = "1";
oClass4.Credit = 1;
oClass4.Debit = 1000;
oList.Add(oClass4);
Class1 oClass1 = new Class1();
oClass1.Name1 = "Person B";
oClass1.Id = "ldc";
oClass1.ParentId = "xyz";
oClass1.Credit = 1;
oClass1.Debit = 2000;
oList.Add(oClass1);
Class1 oClass2 = new Class1();
oClass2.Name1 = "Person C";
oClass2.Id = "ccc";
oClass2.ParentId = "xyz";
oClass2.Credit = 1;
oClass2.Debit = 1000;
oList.Add(oClass2);
Class1 oClass5 = new Class1();
oClass5.Name1 = "Person A";
oClass5.Id = "mno";
oClass5.ParentId = "xyz";
oClass5.Credit = 1;
oClass5.Debit = 1000;
oList.Add(oClass5);
return oList;
}
}
}
please help me to do this
in tag section of question i added objectlistview but i want to show details on
dataTreeListview
You can use linq to filter by the parent and then sum the list like so:
public static float SumChildren(string parentKey){
return GetList().Where(x => x.ParentId == parentKey).Sum(x => x.Debit)
}
You may have to switch the return type, but I'm assuming Debit is a decimal
Based on your comments your code requires a bigger refactor. You should be adding the data through a method and have that method update the parent debit value based off of the children added.
But As a quick hack you can just assign the parent value, but if you're going to do this for multi-nest trees you'll need to start at the deepest branch and work your way up.
var parentDebitValue = SumChildren("xyz");
GetList().Where(x => x.Id == "xyz").First().Debit = parentDebitValue;
But realisticly you should re achitect your program
This Is the class I have
public class Income
{
public string Code { get; set; }
public int Month1 { get; set; }
public int Month2 { get; set; }
public int Month3 { get; set; }
public int Month4 { get; set; }
public int Month5 { get; set; }
public List<Income> income { get; set; }
}
In the other class
List<Income> incomeList = new List<Income>();
//repeat twice
Income obj = new Income();
obj.Month1 = 200;
obj.Month2 = 150;
...
IncomeList.Add(obj);
obj.income = IncomeList;
Now I want to retrieve those Months in a loop for each new obj saved in a
List.
So far
Int[] results = obj.income
.Select(x=> new
{
x.Month1,
x.Month2,
x.Month3,
x.Month4,
x.Month5
})
.ToArray();
This is where I need to add the total months for each unique object.
get The total for All Months1 , Months2 ...
double totals[] = new double[5];
for (int i=0;i<results.length;i++)
{
totals[i] += results[i]; // I get the first object reference
// I want Moth1,Month2 ... to be in an indexed array where
// if i want Month1 i would access similar to : results[index];
}
Ok, the following code will project out a list of objects. Each object will have a single property called "Months" which is an int[] of the month values.
Does that do what you need?
void Main()
{
var incomeList = new List<Income>();
Income obj = new Income();
obj.Month1 = 200;
obj.Month2 = 150;
incomeList.Add(obj);
var results = incomeList
.Select(x => new
{
Months = new int[]
{
x.Month1,
x.Month2,
x.Month3,
x.Month4,
x.Month5
}
})
.ToArray();
for (int i = 0; i < results.Length; i++)
{
var testResults = results[i];
Console.WriteLine($"Month 1: {testResults.Months[0]}");
Console.WriteLine($"Month 2: {testResults.Months[1]}");
Console.WriteLine($"Month 3: {testResults.Months[2]}");
Console.WriteLine($"Month 4: {testResults.Months[3]}");
Console.WriteLine($"Month 5: {testResults.Months[4]}");
}
}
However, given your comments in the posted code, I think you want to to turn it into a 2-dimensional array. If so, simply project out an int[]:
void Main()
{
var incomeList = new List<Income>();
Income obj = new Income();
obj.Month1 = 200;
obj.Month2 = 150;
incomeList.Add(obj);
int[][] results = incomeList
.Select(x => new int[]
{
x.Month1,
x.Month2,
x.Month3,
x.Month4,
x.Month5
})
.ToArray();
for (int i = 0; i < results.Length; i++)
{
var testResults = results[i];
Console.WriteLine($"Month 1: {testResults[0]}");
Console.WriteLine($"Month 2: {testResults[1]}");
Console.WriteLine($"Month 3: {testResults[2]}");
Console.WriteLine($"Month 4: {testResults[3]}");
Console.WriteLine($"Month 5: {testResults[4]}");
}
}
I have a list that contains elements. The user should be able to search for specific element and the list. Then list should print out all lines that contains this specific element. Why is this not working?
Car search = new Car();
public void SearchLog()
{
for (int i = 0; i < myList.Count; i++)
{
if (myList[i].Model== search.Model)
{
Console.WriteLine("Model :" + search.Model)
}
}
}
Console.Write("Search for model:");
search.searchModel = Console.ReadLine();
It's working now! Always something new to learn. The issue was my class variable. So I used variable from same scope instead.
I have complete code for you based on the information from the question and comments:
This will be the sample class for Car;
class Car
{
public string Model { get; set; }
public string Name { get; set; }
public string Brand { get; set; }
//Rest of properties here
public override string ToString()
{
string output = String.Format("Model :{0} \n Name :{1} \n Brand :{2}", this.Model, this.Name, this.Brand);
return output;
}
}
Here is the main function that do the operations:
public static List<Car> myList = new List<Car>();
static void Main(string[] args)
{
myList.Add(new Car() { Model = "A", Name = "XXX", Brand = "Some Brand" });
myList.Add(new Car() { Model = "B", Name = "YYY", Brand = "Some Brand1" });
myList.Add(new Car() { Model = "C", Name = "ZZZ", Brand = "Some Brand2" });
Car search = new Car();
Console.Write("Search for model:");
search.Model = Console.ReadLine();
Console.WriteLine("Following Result Found for {0}", search.Model);
SearchLog(search);
}
Finally the signature for SearchLog is:
public static void SearchLog(Car search)
{
var resultList = myList.Where(x => x.Model == search.Model).ToList();
int i = 1;
foreach (var car in resultList)
{
Console.WriteLine("Result {0} : {1}", i++, myList[i].ToString());
}
}
I have another suggestion; The search need not be an object of the class Car It can be a string instead;
You can try it in your own way like the following:
Console.Write("Search for model:");
string inputSearch = Console.ReadLine();
bool carFound = false;
for (int i = 0; i < myList.Count; i++)
{
if (myList[i].Model == inputSearch)
{
Console.WriteLine("Model: " + myList[i].Model);
carFound = true;
}
}
if (!carFound) { Console.WriteLine("None model were found"); }
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]));
}