c# – 如何查看列表中存储的值?

我正在尝试学习如何在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.

有几种方法可以搜索List< T>,这里有两种:

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;

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...