微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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;

原文地址:https://www.jb51.cc/csharp/91435.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐