Add values to Dictionary<int,class> not all at once - c#

I'm trying to store data in a dictionary where the key is an ID and the values are of a class type. The class properties are not all added at the same time so I haven't used a constructor - unless there is a way to add new values using a constructor at a different times? The code below compiles, but I get a run time error saying the key has already been added.Thanks for the help.
public class Students
{
public string FirstName { get; set; }
public string SurName { get; set; }
public int Age { get; set; }
public double Score { get; set; }
}
public void cmdTEST_Click(object sender, EventArgs e)
{
Dictionary<int, Students> Data = new Dictionary<int, Students>();
Data.Add(5, new Students { FirstName = "Bob" });
Data.Add(5, new Students { Age = 34 }); // run time error - "key already added"
Data.Add(5, new Students { Score = 62 });
// extract data
double Score5 = Data[5].Score;
double Age5 = Data[5].Age;
}

You are adding same key multiple times which is not allowed. You can add all properties at once like below
Dictionary<int, Students> Data = new Dictionary<int, Students>();
Data.Add(5, new Students { FirstName = "Bob", Age = 34, Score = 62 });
And if you want to add values later you can use key to add values
Data.Add(5, new Students { FirstName = "Bob"});
Data[5].Age = 34;
Data[5].Score = 62;

Related

How to bind nested list to datagridview in winforms

I am creating app in windows form. Below mentioned is structure of my list that I am going to bind to DataGridView. I have main list(Student) and inside main list, I have child list(Book) that is to be bind to DataGrid View. So, main list will have Id(int), Name(string) and lstBk(list which is child list).
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public List<Book> lstBk { get; set; }
}
public class Book
{
public int ID { get; set; }
public string Name{ get; set; }
}
Whenever I bind list to datagrid view, I am getting Id and Name only but not lstBk in grid view row. How do I get lstBk after ID and Name in datagrid view?
List<Book> lst = new List<Book>();
lst.Add(new Book() { ID= 1, Name ="Book 1" } );
lst.Add(new Book() { ID = 2, Name = "Book 2" });
lst.Add(new Book() { ID = 3, Name = "Book 3" });
List<Student> lstUD = new List<Student>();
lstUD.Add(new Student() { ID = 1, Name = "First Name1", lstBk = lst });
lstUD.Add(new Student() { ID = 2, Name = "First Name2", lstBk = lst });
dataGridView1.DataSource = lstUD;
One possible solution is to “flatten” the Book list. If we override the Books ToString method to output the books ID and Name... then we could then add a property to the Student class that creates a single string from all the Books in the list. Something like…
Book Class…
public class Book {
public int ID { get; set; }
public string Name { get; set; }
public override string ToString() {
return ID + " - " + Name;
}
}
Then create a new string property ListOfBooks in the Student Class. This will get shown in the grid. Something like...
public class Student {
public int ID { get; set; }
public string Name { get; set; }
public List<Book> lstBk { get; set; }
public string ListOfBooks {
get {
return string.Join(", ", lstBk);
}
}
}
This will put all the books from the list into a single cell in the grid. If there is too much data in the cell, then I would suggest using a master-detail with two grids. One for the student and another to display the books from the “selected” student in the “student/Master” grid.
Using a Master-Detail with two grids.
Create a new winforms project, drop a couple of DataGridViews onto the form and the code below should demonstrate one way to implement a Master-Detail using the classes you have posted.
In this case, the Book ToString override is obviously not needed in addition to the added ListOfBooks property in the Student class. They may look like the original post…
public class Book {
public int ID { get; set; }
public string Name { get; set; }
}
public class Student {
public int ID { get; set; }
public string Name { get; set; }
public List<Book> lstBk { get; set; }
}
We will need some mechanism to “signal” when the user “selects” a different cell in the “Student/Master” grid. For this, we will wire up the grids SelectionChanged event. In that event, the code "cast" the selected Student in the grid to a Student object, then uses the Students lstBk list to display into the “Book/Details” grid. This event may look something like below…
private void dataGridView1_SelectionChanged(object sender, EventArgs e) {
Student student = (Student)dataGridView1.CurrentRow.DataBoundItem;
dataGridView2.DataSource = student.lstBk;
}
When the grids are loaded, the details grid is filled using the first row in the master grid as in most cases, this is the default selected cell.
To complete this example, 10 Students are added to the “Student/Master” grid such that each student has a random number of books between 1 and 6.
List<Student> AllStudents;
Random rand;
public Form1() {
InitializeComponent();
dataGridView1.SelectionChanged += new EventHandler(dataGridView1_SelectionChanged);
AllStudents = new List<Student>();
rand = new Random();
}
private void Form1_Load(object sender, EventArgs e) {
for (int i = 1; i < 11; i++) {
AllStudents.Add(GetStudent(i, "Student_" + i + 1));
}
dataGridView1.DataSource = AllStudents;
dataGridView2.DataSource = AllStudents[0].lstBk;
}
private Student GetStudent(int studentID, string name) {
int numberOfBooks = rand.Next(1, 7);
int bookNumber;
List<Book> books = new List<Book>();
for (int i = 0; i < numberOfBooks; i++) {
bookNumber = rand.Next(1, 10000);
books.Add(new Book { ID = bookNumber, Name = "Book" + bookNumber });
}
return new Student { ID = studentID, Name = name, lstBk = books };
}
I hope this makes sense.

DataGridView not displaying properties containing Lists

I have an object like so
public class Person{
public int ID { get; set; }
public string Name{ get; set; }
public string Surname{ get; set; }
public List<int> AltIDs { get; set; }
public List<string> AltNames{ get; set; }
}
I am setting data into the DataGridView like
dataGridView1.DataSource = null;
dataGridView1.DataSource = persons; // persons is List<Person>
However I only see 3 columns in the DataGridView that is of ID, Name and Surname, the properties with List<int> and List<string> seem to be ignored.
Is there a way to get theses properties showing up in the DataGridView? Probably like comma seperated values.
most probably the persons is null
you just change your code like this code
first Solution :
your model :
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public List<int> AltIDs { get; set; }
public List<string> AltNames { get; set; }
}
PersonViewModel :
public class PersonViewModel
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int AltID { get; set; }
public string AltName { get; set; }
}
formLoad :
private void Form1_Load(object sender, EventArgs e)
{
List<Person> people = new List<Person>()
{new Person(){ ID=1,Name="a",Surname="a",AltIDs=new List<int>(){1,2,3,4 },AltNames=new List<string>(){"a","b","c" } },
new Person(){ ID=2,Name="b",Surname="b",AltIDs=new List<int>(){10,20,30,40 },AltNames=new List<string>(){"a","b","c" }},
new Person(){ ID=3,Name="c",Surname="c",AltIDs=new List<int>(){100,200,300,400 },AltNames=new List<string>(){"a","b","c" }},
new Person(){ ID=4,Name="d",Surname="d",AltIDs=new List<int>(){1000,2000,3000,4000 },AltNames=new List<string>(){"a","b","c" }},
new Person(){ ID=3,Name="e",Surname="e",AltIDs=new List<int>(){10000,20000,30000,40000 },AltNames=new List<string>(){"a","b","c" }}
};
List<PersonViewModel> pwm = new List<PersonViewModel>();
foreach (var person in people)
{
foreach(var id in person.AltIDs)
{
foreach (var name in person.AltNames)
pwm.Add(new PersonViewModel() { ID = person.ID, Name = person.Name, Surname = person.Surname, AltID = id, AltName = name });
}
}
dgv.DataSource = pwm;
}
Result :
Second Solution :
your model :
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public List<int> AltIDs { get; set; }
public List<string> AltNames { get; set; }
}
PersonViewModel :
public class PersonViewModel
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string AltID { get; set; }
public string AltName { get; set; }
}
FormLoad :
private void Form1_Load(object sender, EventArgs e)
{
List<Person> people = new List<Person>()
{new Person(){ ID=1,Name="a",Surname="a",AltIDs=new List<int>(){1,2,3,4 },AltNames=new List<string>(){"a","b","c" } },
new Person(){ ID=2,Name="b",Surname="b",AltIDs=new List<int>(){10,20,30,40 },AltNames=new List<string>(){"a","b","c" }},
new Person(){ ID=3,Name="c",Surname="c",AltIDs=new List<int>(){100,200,300,400 },AltNames=new List<string>(){"a","b","c" }},
new Person(){ ID=4,Name="d",Surname="d",AltIDs=new List<int>(){1000,2000,3000,4000 },AltNames=new List<string>(){"a","b","c" }},
new Person(){ ID=3,Name="e",Surname="e",AltIDs=new List<int>(){10000,20000,30000,40000 },AltNames=new List<string>(){"a","b","c" }}
};
List<PersonViewModel> pwm = new List<PersonViewModel>();
StringBuilder sbIds;
StringBuilder sbNames;
foreach (var person in people)
{
sbIds = new StringBuilder();
sbNames = new StringBuilder();
person.AltIDs.ForEach(c=> sbIds.Append(c.ToString()).Append(","));
person.AltNames.ForEach(c=> sbNames.Append(c).Append(","));
pwm.Add(new PersonViewModel() { ID = person.ID, Name = person.Name, Surname = person.Surname, AltID = sbIds.ToString().TrimEnd(','), AltName = sbNames.ToString().TrimEnd(',') });
}
dgv.DataSource = pwm;
}
Result :
When DataGridView is bound to DataSource, it auto generates columns for it for the properties with primitive datatypes such as int, string, double etc.
For the datatypes which are collections, DataGridViewComboBoxColumn is used. This type of column is not autogenerated. You need to add such columns manually in the GridView columns collection.
For your use case following is the solution.
Add DataGridView to the form and add columns to it manually from the Form's designer view by click on Add Column. You will have to add 3 DataGridViewTextBoxColumn and 2 DataGridViewComboBoxColumn.
After adding columns, the columns would look as following.
Now while assigning DataSource to the DataGridView you need to write following code. Here IdColumn, NameColumn, and SurnameColumn are the names give to columns when they were created in above steps.
dataGridView1.AutoGenerateColumns = false;
IdColumn.DataPropertyName = "ID";
NameColumn.DataPropertyName = "Name";
SurnameColumn.DataPropertyName = "Surname";
dataGridView1.DataSource = persons;
With the above code you will see Id, Name and Surname columns populated for persons in the collection but the dropdown lists in last two columns are empty.
To populate the dropdown list columns you need to add event handler for CellClick event of the DataGridView. And write following code there.
Here AltIdsColumn and AltNamesColumn are the names given to column when they created manually in earlier steps.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
var altIdIndex = dataGridView1.Columns["AltIdsColumn"].Index;
var altNameIndex = dataGridView1.Columns["AltNamesColumn"].Index;
if (altIdIndex == e.ColumnIndex || altNameIndex == e.ColumnIndex)
{
var altIdsCell = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[altIdIndex];
var altNamesCell = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[altNameIndex];
if (altIdsCell.DataSource == null || altNamesCell.DataSource == null)
{
var person = dataGridView1.Rows[e.RowIndex].DataBoundItem as Person;
if (person != null)
{
altIdsCell.DataSource = person.AltIDs;
altNamesCell.DataSource = person.AltNames;
}
}
}
}
With this code, the dropdown list of AldIDs and AltNames columns will be populated when you click on those dropdown lists on individual rows.
I hope this will help you resolve your issue.
From what I can tell, this appears as a fairly basic “Master/Slave” type UI. In the grid, there is a “Person” object with the ID, Name and Surname. Obviously from your question, the AltIDs and AltNames Lists are NOT displayed in the grid.
This is due to the fact that the grid has a problem trying to add a “list of multiple” values into a “single” cell. As suggested, it is possible for you to “combine” the values into a “single” string and use that. However, this is extra work on your part and may create more work if the cell is edited.
One issue in this example is that, the AltIDs list for each Person could and will have a different number of elements. One possible solution is to simply ADD theses as new rows where the Person info (ID, Name and Surname) are duplicated. This will work but IMHO not very user friendly. The combo box option will also work, however again it may be confusing to users since a combo box “usually” indicates that the users selects a “single” value from many.
It is also possible to “flatten” each person object and have a column for each AltID in the list. This will work but the possibility of large gaps in the grid are likely. Again, not very user friendly. This is all doubled by the fact that there is another list AltNames that we have to take into account.
Given this, it appears clear that YOU are going to have to do extra work UNLESS you use an advanced third-party grid OR add more grids to the picture… in this case three (3) total. One for the person, another for the IDs and a third for the Names. Proper arrangement of the grids may be a little work, however, with three grids, it will make all the issues described above… go away. In addition the coding will be much easier.
It would be such that the user “selects” a Person from the first grid, then the second grid list all the AltID values and the third grid lists all the AltName values. If the “same” data source is used for each grid then… when the user selects a different Person in the person grid, the AltID grid and AltName grid will “automatically” update/refresh with the proper values. This will also make CRUD operations on any grid/value much easier.
The only problem I seen in the current Person class is that the two Lists are of “primitive” types. Used this way, the lists won’t display properly, the grid wants a CLASS. Therefore, you need to make a wrapper class for the AltID and AltName lists. Then change the list values in the Person class. Something like…
public class AltID_C {
public int AltID { get; set; }
}
public class AltName_C {
public string AltName { get; set; }
}
public class Person {
public int ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public List<AltID_C> AltIDs { get; set; }
public List<AltName_C> AltNames { get; set; }
}
With this, all that is needed is to set each grid to the “same” data source, then set the AltID grids DataMember to the “AltIDs” property and set the AltNames grids DataMember to the “AltNames` property. Something like…
List<Person> AllPersons;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
AllPersons = GetRandomData(25);
dgvPerson.DataSource = AllPersons;
dgvAltID.DataSource = AllPersons;
dgvAltID.DataMember = "AltIDs";
dgvAltNames.DataSource = AllPersons;
dgvAltNames.DataMember = "AltNames";
}
Additional code below to complete the example.
private List<Person> GetRandomData(int numberOfPersons) {
List<Person> listOPeople = new List<Person>();
Person curPerson;
Random rand = new Random();
for (int i = 0; i < numberOfPersons - 1; i++) {
curPerson = new Person() {
ID = rand.Next(1, 1000),
Name = "Name_" + i + 1,
Surname = "Sname_" + i + 1,
AltIDs = GetRandomNumberOfInts(rand),
AltNames = GetRandomNumberOfStrings(rand)
};
listOPeople.Add(curPerson);
}
return listOPeople;
}
private List<AltID_C> GetRandomNumberOfInts(Random rand) {
List<AltID_C> listOInts = new List<AltID_C>();
int numberOfInts = rand.Next(0, 10);
for (int i = 0; i < numberOfInts - 1; i++) {
listOInts.Add(new AltID_C { AltID = rand.Next(1, 10000) });
}
return listOInts;
}
private List<AltName_C> GetRandomNumberOfStrings(Random rand) {
List<AltName_C> listOStrings = new List<AltName_C>();
int numberOfStrings = rand.Next(0, 10);
for (int i = 0; i < numberOfStrings - 1; i++) {
listOStrings.Add(new AltName_C { AltName = "RandString: " + rand.Next(1, 1000) });
}
return listOStrings;
}
Hope that helps.

Convert List to List<Dictionary> efficiently without foreach in c# [duplicate]

This question already has answers here:
How can I convert a class into Dictionary<string,string>?
(8 answers)
Closed 4 years ago.
Assume I have a list of class
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
Now i need to convert into List of Dictionary as
Assume it as List<Dictionary<key, value>>PersonDict, below is the structure of each indexes of the same. The key name should be dynamically populated as Property name in the class Person.
key : "Id", Value : Person.Id
key : "Name", Value : Person.Name
key : "Age", Value : Person.Age
Can anyone please help, I have already tried "for each" and "Parallel For each" loop but its taking lot of time, I have 3 millions of record to convert and its taking hours.
Here is a working implementation:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// Create some sample records
var persons = new List<Person>(){
new Person(){Id = 1, Name = "Bob", Age = 30},
new Person(){Id = 2, Name = "Jane", Age = 31},
new Person(){Id = 3, Name = "Mary", Age = 32}
};
// Use Reflection to retrieve public properties
var properties = typeof(Person).GetProperties();
// Create a list to store the dictionaries
var listOfDictionary = new List<Dictionary<string, string>>();
// For each person class
foreach(var person in persons){
// Create a new dictionary
var dict = new Dictionary<string,string>();
// For each property
foreach(var prop in properties){
// Add the name and value of the property to the dictionary
dict.Add(prop.Name, prop.GetValue(person).ToString());
}
// Add new dictionary to our list
listOfDictionary.Add(dict);
}
// Check the contents of our list
foreach(var dict in listOfDictionary){
Console.WriteLine(string.Join(",", dict.Keys));
Console.WriteLine(string.Join(",", dict.Values));
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
}
You mention that you have millions of records to convert. It may be not the best idea to create millions of Dictionary<> instances, nor to keep them all in memory. However, it is difficult to recommend something without knowing what is your end goal.
This is pretty much the same as the other answers here, but using a slightly more terse syntax. Just a matter of preference.
List<Person> persons = new List<Person> {
new Person { Id = 1, Name = "Sally", Age = 10 },
new Person { Id = 2, Name = "Bob", Age = 9 },
};
List<Dictionary<string, string>> listOfDictionaries =
persons
.Select(p => new Dictionary<string, string>
{
["Id"] = p.Id.ToString(),
["Name"] = p.Name,
["Age"] = p.Age.ToString(),
})
.ToList();

how can I add a value to the list from the Dictionary<int,Object> and the list is in the Object

Ok.. I've seen some similar discussions so I hope this is unique enough.
I would like to initialize and modify data in a List
The list is a Property of the class User, which is inside a Dictionary
http://ideone.com/0YtpnC
internal class User
{
public string ID { get; set; }
public string Name { get; set; }
public List<ContactNumber> AddressBook { get; set; }
}
internal class Program
{
private static void Main(string[] args)
{
Dictionary<int, User> dic = new Dictionary<int, User>();
dic.Add(1, new User { ID = "id1", Name = "name1" });
dic.Add(2, new User { ID = "id2", Name = "name2" });
dic.Add(3, new User { ID = "id3", Name = "name3", AddressBook = new List<ContactNumber>(){new ContactNumber(3432),new ContactNumber(3213)} });
User user = dic.Where(z => z.Value.ID == "id3").FirstOrDefault().Value;
Console.WriteLine(user.Name);
DisplayList(user);
//Console.WriteLine(user.AddressBook.ToString());
//update the list
addOrUpdate(dic,3,user);
//var used = new User { ID = "id1", Name = "Harry" };
//dic[1] = used;
user = dic.Where(z => z.Value.ID == "id3").FirstOrDefault().Value;
Console.WriteLine(user.Name);
DisplayList(user);
}
private static void DisplayList(User user)
{
foreach (ContactNumber number in user.AddressBook)
{
Console.WriteLine(number.PhoneNumber);
}
}
//determin list length
public static void addOrUpdate(Dictionary<int, User> dic, int key, User user)
{
//sets a new user data and just replaces it in the dictionary
//var used = new User { ID = "id1", Name = "Harry" };
var used = new User{ ID = "id3", Name = "Henry" ,AddressBook = new List<ContactNumber>(){new ContactNumber(3111),new ContactNumber(4444)}};
if (dic.TryGetValue(key, out user))
{
// yay, value exists!
dic[key] = used;
}
else
{
// darn, lets add the value
dic.Add(key, used);
}
}
}
the problem is I want to get the user info and just add a contact number to the list. Currently it rewrites the entire list since I make a new version of list in the update function.
http://ideone.com/iI2Rxb
Simply:
dic[key].AddressBook.Add(new ContactNumber(666));
This seems to be a solution.
user.AddressBook.Add(new ContactNumber() { PhoneNumber = 121212});
from MSDN Docs
Wont below help, just add to the list (since it is referenced, it will update whatever you have been getting from the dictionary)
user.AddressBook.Add(...new contact number);

c# Nested Dictionary, better alternative? best organize data across three classes

Suppose
There is a Trend class.
public class Trend{
public string TrendName { get; set; }
public string Description { get; set; }
}
e.g.
new Trend() { TrendName= "Pizza", Description="yum yum" };
new Trend() { TrendName= "Clothing", Description="ba yum" };
new Trend() { TrendName= "Food" };
There is a Person class.
public class Person {
public string PersonName { get; }
public int PersonId { get; }
public int aptitude { get; }
...... many other properties
}
e.g.
new Person() { PersonName = "Arnold Palmer" };
new Person() { PersonName = "Ken Hemingway" };
There is a thing class.
public class TrendyItem
{
public string ItemName { get; }
public string ItemId { get; }
}
e.g.
new TrendyItem() { ItemName = "PotatoPizza" }
new TrendyItem() { ItemName = "PeplumSkirt" }
There is a TrendysOfYear class. This class already has.
public class TrendProfile
{
public List<Trend> FavoriteTrendsOfYear;
public List<Person> ActivePeopleThisYear;
public List<TrendyItem> TrendyItemsThisYear;
}
For every TrendysOfYear,
There will be a list of different trends, FavoriteTrendsOfYear,
each person belonging to the ActivePeopleThisYear
will specifiy a "TrendyItem"
Given a TrendProfile, I want to be able to be able to quickly look up
1) Input: Person; Output: List of Person's choice on trendy items.
2) Input: Trend; Output: List of trendy items belonging to that trend.
I've considered two ways.
A) Dictionary<Person, Dictionary<Trend, TrendyItem>>
You can get PersonsChoiceOnTrendyItem = dic[Person].Values.ToList();
but have to loop through and build new list everytime you look up TrendyItemsOfTrend.
B) Dictionary<Trend, Dictionary<Person, TrendyItem>>
vice cesra.
Is it a good practice to use these custom objects for dictionary keys?
Is it a good practice to use nested dictionaries?
What's the best way to map items in this case?
Also, not that Trend class does not have integer Id, so will have to used the string (the name of the trend is guaranteed to be unique) as key.
Additional Info: properties of Trend such as TrendName and Description are editable. So i'm a little hesitant to add collection of TrendyItems to Trend class. If there is Trend, "Fashionn" in TrendProfile1 and TrendProfile2, and someone decides to change the name to "Fashion", I want both profiles to reference the same object.
Typically you don't see the objects that contain values used as keys in this way. Usually you will identify some unique key on your object and use that as key and the object itself as the value. For example you could store Person objects in a Dictionary where the person's name is the key, and Person is the value.
Instead of nested Dictionaries, you should consider adding Collections to your objects. For example, you could add a List<TrendyItem> to Trend to maintain that relationship.
Here is an alternative way that you could organize the classes. I'm not exactly sure what the scope is of each of your collections, but this should give you another way to look at the problem.
public class Trend
{
public string TrendName { get; set; }
public string Description { get; set; }
// This maintains the relationship between Trend and TrendyItem
public List<TrendyItem> Items { get; set; }
}
public class Person
{
public string PersonName { get; set; }
public int PersonId { get; set; }
public int aptitude { get; set; }
// Each person will specifiy a "TrendyItem"
public TrendyItem Choice { get; set; }
}
public class TrendyItem
{
public string ItemName { get; set; }
public string ItemId { get; set; }
}
public class TrendProfile
{
// Change this to to a key value pair. The key will be how you uniquely identify (input) the Trend in
//2) Input: Trend; Output: List of trendy items belonging to that trend.
// For example TrendName
public Dictionary<string, Trend> FavoriteTrendsOfYear;
// Change this to to a key value pair. The key will be how you uniquely identify (input) the Person in
// 1) Input: Person; Output: List of Person's choice on trendy items.
// For example PersonName
public Dictionary<string, Person> ActivePeopleThisYear;
public List<TrendyItem> TrendyItemsThisYear;
}
With that class structure, you can easily answer the questions in your post.
static void Main()
{
TrendProfile trendProfile = new TrendProfile();
trendProfile.FavoriteTrendsOfYear = new Dictionary<string, Trend> {
{ "Pizza", new Trend() {
TrendName = "Pizza",
Description = "yum yum",
Items = new List<TrendyItem> {
new TrendyItem() {ItemName = "PotatoPizza1"},
new TrendyItem() {ItemName = "PotatoPizza2"},
new TrendyItem() {ItemName = "PotatoPizza3"}
}
}},
{ "Clothing", new Trend() {
TrendName = "Clothing",
Description = "ba yum",
Items = new List<TrendyItem> {
new TrendyItem() {ItemName = "PeplumSkirt1"},
new TrendyItem() {ItemName = "PeplumSkirt2"},
new TrendyItem() {ItemName = "PeplumSkirt3"}
}
}}
};
trendProfile.ActivePeopleThisYear = new Dictionary<string, Person> {
{ "Arnold Palmer", new Person() { PersonName = "Arnold Palmer", Choice = trendProfile.FavoriteTrendsOfYear["Pizza"].Items[1] }},
{ "Ken Hemingway", new Person() { PersonName = "Ken Hemingway", Choice = trendProfile.FavoriteTrendsOfYear["Clothing"].Items[2] }},
};
//1) Input: Person; Output: List of Person's choice on trendy items.
string person = "Arnold Palmer";
Console.WriteLine(trendProfile.ActivePeopleThisYear[person].Choice.ItemName);
//2) Input: Trend; Output: List of trendy items belonging to that trend.
string trend = "Clothing";
foreach(TrendyItem item in trendProfile.FavoriteTrendsOfYear[trend].Items)
Console.WriteLine(item.ItemName);
}
UPDATE
To share Trends across TrendProfiles, you could first create a "master" List or Dictionary of Trends. Then when building each of the TrendProfliles, you could pick the Trends out of the "master".
// "Master" list of trends
List<Trend> trends = new List<Trend> {
new Trend() {
TrendName = "Pizza",
Description = "yum yum",
Items = new List<TrendyItem> {
new TrendyItem() {ItemName = "PotatoPizza1"},
new TrendyItem() {ItemName = "PotatoPizza2"},
new TrendyItem() {ItemName = "PotatoPizza3"}
}
},
new Trend() {
TrendName = "Clothing",
Description = "ba yum",
Items = new List<TrendyItem> {
new TrendyItem() {ItemName = "PeplumSkirt1"},
new TrendyItem() {ItemName = "PeplumSkirt2"},
new TrendyItem() {ItemName = "PeplumSkirt3"}
}
}
};
TrendProfile trendProfile1 = new TrendProfile();
trendProfile1.FavoriteTrendsOfYear = new Dictionary<string, Trend> {
{ trends[0].TrendName, trends[0] },
{ trends[1].TrendName, trends[1] }
};
TrendProfile trendProfile2 = new TrendProfile();
trendProfile2.FavoriteTrendsOfYear = new Dictionary<string, Trend> {
{ trends[1].TrendName, trends[1] }
};

Categories

Resources