Access members of a list without looping through it - c#

I need to create a list with more than 400 items and each item has 3 properties, in c#. Like:
Name
Profession
Age
Marital Status
The relevant detail is that, to access individual data, I do not want to loop over each Name with a foreach or something else, but I want to access the data directly.
Assuming I need data from a person called Ana_Salgado, which name is stored in a string called PersonName, would it be possible to access these data like: PersonName.Profession?
Any ideas? Thank you in advance :)

You can use Dictionary, in this way
Class Members
{
public string Profession {get; set;}
public string Age {get; set;}
public string MaritalStatus {get; set;}
}
Dictionary<string, Members> dict = new Dictionary<string, Members>();
In this way you have a data model where the name is the key of your dictionary, and
you can use dict["Ana_Salgado"].Age or any of Members property.

Use Dictionary instead of list for example. And then you would be able write something like myDictionary["Ana_Salgado"].Profession

Related

Visual Studio C# Watch window and arrays

I'm currently investigating some problems with a list (or array, I'm using "list" in this post equally to an array because an array can be converted to a list when needed)
For example I have
List<Car> cars = new List<Cars>();
My Car object is made this way
public class Car
{
public double Weight {get; set;}
public double TopSpeed {get; set;}
public int NumberOfPassengers {get; set;}
public string ModelName {get; set;}
}
In the watch list I want to see the items of the list but only care about the ModelName property. Is there any way to show me the expanded list in the watch list and only show the ModelName property?
Currently when I expand the list It shows me that it contains 4 elements and in the Value column it only shows me (somename.namespace.Car). So I need to expand every element of the list further to see all properties but this is getting messy if the list gets longer or there are many elements in the list. One constraint --> the class Car is not under my control and therefore I can't overwrite its ToString() method or use [DebuggerDisplay()].
I tried using Linq ForEach(x => Console.write(x.modelName) but that is not working.
I'm happy about any advice or tip :-)
Thanks to #nilsK hint. I found this solution:
Simply using this watch expression:
myListWithCars.Select(x => x.modelName).ToList()

Sending back a different model from the view

I want to send details of 2 different models to the view so I do this with a view model.
namespace Apps.Models
{
public class viewmodel1
{
public App app { get; set; }
public List<Colleague> colleague { get; set; }
}
}
app being a model that stores a variety of properties about an application, and colleague being a model that stores a variety of properties about colleagues.
Originally I was only passing in app, but I want to be able to display a drop down list of the colleagues first names in this view when creating an app (because the two are linked) so i need to pass in all the current colleagues to get their first names. This part is working.
However, my action result needs to change when the form is submitted to take in this new viewmodel type, and I don't know how to access the properties from the action result. Normally when you bind include there are just properties in the model, but i want to include the properties that are WITHIN the objects the viewmodel has. I don't know how to do this or of i am just doing something wrong.
I would obviously like to retain the validation that is already written for the app properties, but I'm not sure I can do that this way.
Not sure if this is the answer to your question without seeing the xaml binding you are trying to use, but you can use bindings that dive into objects.
So if you have an Employee object that is your DataContext (Employee would be your ViewModel although it has no controller logic, so I guess it's just a model here):
public class Employee
{
public string Name {get; set;}
public EmpAddress Address {get; set;}
}
public class EmpAddress
{
public string Street {get; set;}
public string Zip {get; set;
}
You can do bindings that look like this:
<TextBlock Text={Binding Address.Street}/>
Let me know if this isn't what you were after and I'll try to help.

How to create a single drop down for multiple data types?

I am using ASP.Net MVC 3 and I need to create a single drop down list which contains items that relate to multiple database tables.
Normally, if I need to do a drop down list for a single data type I can easily use the ID as the "value" for each drop down option and would do something like this:
#Html.DropDownListFor(x => x.SelectedID, Model.GetMyList())
But now I want to mix up multiple data types. So lets say for this example I want to create a single list to represent something like "Owner" and this can be either a "User" or a "Customer". In this example, both User and Customer are separate database tables and therefore the ID value alone is not enough to identify them correctly.
So what are the best ways to achieve such functionality?
Straight off the top of my head, my first thoughts are to create a "custom" value string which could then be parsed server side to work out the ID and data type, something like...
"USER|1"
"CUSTOMER|1"
I know I can make this work, but am I making this more complicated than it needs to be? Is there a built-in or advised way of doing this?
In your Model can you not do something like this:-
public class Model
{
public string Owner { get; set; }
public List<MyList> ListCollection { get; set; }
public class MyList
{
public int Id { get; set; }
public string Value { get; set; }
}
}
So then when you are checking which list item is selected you also have access to the "Owner" field which will tell you what table it belongs to ?
As nobody has come up with anything better, I can confirm that my original idea (as unwanted as it was) did the job.
When setting the value of the select options, a custom string should be created that can easily be parsed server side, this was achieved using a pipe separating the TYPE of entity, and the ID, for example:
"USER|1"
"USER|2"
"CUSTOMER|1"
"CUSTOMER|2"
Once the selected value is passed to the server, it can then be parsed something like the following:
string option = "USER|1";
string[] values = option.Split('|');
string entityType = values[0];
int entityId = Int.Parse(values[1]);
which can then be used something like this:
if(entityType == "USER")
UpdateUser(entityId);
else//CUSTOMER
UpdateCustomer(entityId);

issue with Linked List

i wan to create a linked list that contains the name , age and address of some people , so far i created that code :
LinkedList<string> details = new LinkedList<string>();
details.AddFirst("Name1");
details.AddLast("Name2");
details.AddLast("Name3");
foreach (var display in details)
{
Console.WriteLine(display);
}
ok so now it works fine , but i just input the name , how can i input the age and address , is it like array ? i just don`t know much about linkedlists , and also i tried to delete some nodes of the linkedlist but i failed :
foreach (var item in details)
{
if (item.Contains("Name3"))
{
details.Remove(item);
}
}
but i get that error :
Unhandled Exception: System.InvalidOperationException: Collection was modified after the enumerator was instantiated.
and finally , how can i edit a linkedlist item , like renaming Name2 to Name13 or anything , i would really appreciate any help , just give me idea and i`ll continue digging . Thanks in advance .
You can't remove elements from the list while iterating a list using foreach loop.
if (details.Remove("Name3"))
Console.WriteLine("Removed");
else
Console.WriteLine("Not Found");
A linked list is like an array in that it is a collection of data. Each item in the list stores a link to the next item (and often the previous), hence the name.
You can't modify a list you're looping over, because your reference into the list will then be invalid.
If you wish to add extra information within the list, simply create a class which encapsulates that information, as the LinkedList is a generic type. For example:
//Structure to hold extra information
public class PersonDetails
{
public string Name {get; private set;}
public int Age {get; private set;}
public string Address {get; private set;}
//Constructor
public PersonDetails(string name, int age, string address)
{
this.Name = name;
this.Age = age;
this.Address = address;
}
}
Then you can create a new linked list containing those types:
LinkedList<PersonDetails> list = new LinkedList<PersonDetails>();
list.AddFirst(new PersonDetails("Name", 22, "Address"));
Note that you cannot modify a collection when you are enumerating it, you need to perform your check and modify it outside of your foreach loop.
If you can use LINQ, you can convert your code to a linq approach such as:
details = details.Where(item => !item.Contains("Name3")).ToList();

Best way to store sets of data (In a table)

I have a client and a server program, and I am currently using hashtables to store the clients Name and IP address when they connect. I now need to add another variable that the client will send to the server when it connects, but as far as I understand it, hashtables only have 2 columns (Key and value). Is there another way I could store this data instead of using hashtables?
You can stick objects into hash tables, or dictionaries.
So make yourself a user class of some description and then store your user object in your dictionary under their name.
This would then lend itself to take other properties as and when you need to add them.
public class User
{
public string Name { get; set; }
public string IPAddress { get; set; }
public string AnotherProperty { get; set;}
}
Dictionary<string, User> userTable = new Dictionary<string, User>();
userTable.Add(userName, new User(){Name = "fred", IPAddress = "127.0.0.1", AnotherProperty = "blah"});
Something like this
You could create a new class specifically for sotring this information e.g.
public class Client
{
private string Name { get; set;}
private string IP { get; set;}
//... etc.
}
Instead of using a HashTable, simply store an instance of the Client class into the Session object (or whatever your using to store the HashTable.)
If you need to store more then one client's details, then use a List<Client>, or a Dictionary if you need to use keys to lookup items. Experiment to see what works for you.
I'm not sure it's the best solution, but just for general knowledge, if you really need a table, you can use DataTable Class which is a part of ADO.NET (which is native to .NET).
The reason this is not advisable is that it doesn't support unique keys, as a dictionary, and that it generally complicates things in your scenario.

Categories

Resources