加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:28:12 所属栏目:百科 来源:网络整理
导读:我正在尝试学习如何在C#中使用列表.有很多教程,但没有一个真正解释如何查看包含记录的列表. 这是我的代码: class ObjectProperties{ public string ObjectNumber { get; set; } public string ObjectComments { get; set; } public string ObjectAddress {
我正在尝试学习如何在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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读