gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:05:56 27 4
gpt4 key购买 nike

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

关于c# - 如何查看存储在列表中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11051704/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com