我正在尝试学习如何在C#中使用列表.有很多教程,但没有一个真正解释如何查看包含记录的列表.
这是我的代码:
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);
我想在消息框中显示值.现在我只是确保信息进入列表.我还想学习如何在列表中找到一个值并获取与其相关的其他信息,例如,我想通过对象编号找到该项目,如果它在列表中,那么它将返回该地址.我也在使用WPF,如果这有所作为.任何帮助将不胜感激.谢谢.
解决方法
最好的方法是在类中重写ToString并使用
string.Join
加入所有记录:
var recordsAsString = string.Join(Environment.NewLine,Properties.Select(p => p.ToString())); MessagBox.Show(recordsAsString);
这是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.
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;