I am trying to learn how to use lists in C#. There are a lot of tutorials out there, but none of them really explain how to view a list that contains a record.
Here is my code:
class ObjectProperties
{
public string ObjectNumber { get; set; }
public string ObjectComments { get; set; }
public string ObjectAddress { get; set; }
}
List<ObjectProperties> Properties = new List<ObjectProperties>();
ObjectProperties record = new ObjectProperties
{
ObjectNumber = txtObjectNumber.Text,
ObjectComments = txtComments.Text,
ObjectAddress = addressCombined,
};
Properties.Add(record);
I want to display the values in a messagebox. Right now I am just making sure the information is going into the list. I also want to learn how to find a value in the list and get the other information that is related to it, such as, I want to find the item by the Object Number and if it is in the list then it will return the address. I am also using WPF, if that makes a difference. Any help will be appreciated. Thank You.
Since lists can contain any Python variable, it can even contain other lists.
We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.
The best way is to override ToString
in your class and use string.Join
to join all your records:
var recordsAsString = string.Join(Environment.NewLine,
Properties.Select(p => p.ToString()));
MessagBox.Show(recordsAsString);
Here's a possible implementation of ToString
:
class ObjectProperties
{
public string ObjectNumber { get; set; }
public string ObjectComments { get; set; }
public string ObjectAddress { get; set; }
public override string ToString()
{
return "ObjectNumber: "
+ ObjectNumber
+ " ObjectComments: "
+ ObjectComments
+ " ObjectAddress: "
+ ObjectAddress;
}
}
I also want to learn how to find a value in the list and get the other information that is related to it, such as, I want to find the item by the Object Number and if it is in the list then it will return the address.
There are several ways to search a List<T>
, here are two:
String numberToFind = "1234";
String addressToFind = null;
// using List<T>.Find method
ObjectProperties obj = Properties.Find(p => p.ObjectNumber == numberToFind);
//using Enumerable.FirstOrDefault method (add using System.Linq)
obj = Properties.FirstOrDefault(p => p.ObjectNumber == numberToFind);
if (obj != null)
addressToFind = obj.ObjectAddress;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With