所以我创建了一个包含字符串、整数和 float 的类。
然后我在这些类型的 main 中声明了一个数组,并将该类型的对象读入其中
现在我需要在该数组中搜索特定值,如果该值匹配,则返回整个对象
我该怎么做呢?
真的很难过
public class cdClass
{
private static string artist = null;
private static string genre = null;
private static string cdTitle = null;
private static float mSRP;
private static int stock;
private static int upc = 0;
//Following functions are public member methods
public void read_cd(string artist, string genre, string cdTitle, float mSRP, int stock, int upc)
{
//cdClass cd = null ;
System.Console.WriteLine("Enter Artist Name: ");
artist = Console.ReadLine();
System.Console.WriteLine("Enter CD Title: ");
cdTitle = Console.ReadLine();
System.Console.WriteLine("Enter Genre Type: ");
genre = Console.ReadLine();
System.Console.WriteLine("Enter Manufacturers Suggested Retal Price: ");
mSRP = float.Parse(Console.ReadLine());
System.Console.WriteLine("Enter UPC Number: ");
upc = int.Parse(Console.ReadLine());
System.Console.WriteLine("Enter Stock: ");
stock = int.Parse(Console.ReadLine());
//return cd;
}
public int get_upc()
{
return upc;
}
主要内容:
//Follwoing cod will initialize an array of Cd's
cdClass[] cdArray = new cdClass[20];
float taxRate = 0;
do
{
int i = 0;
cdClass current_cd = new cdClass();
current_cd.read_cd(artist, genre, cdTitle, mSRP, stock, upc);
cdArray[i] = current_cd;
i++;
} while (businesslogic.question() != 'Y');
buyer = inputfunctions.buyer();
int UPC = inputfunctions.get_upc();
for (int i = 0; i < 20; i++)
{
if (cdArray[i].get_upc() == UPC)
最佳答案
您可以使用简单的 LINQ 扩展方法来搜索对象。
var foundItem = myArray.SingleOrDefault(item => item.intProperty == someValue);
这是一些 MSDN information regarding LINQ让您更加熟悉。
编辑 发布的代码。
我首先想说的是,您似乎正在从一种不同的语言中引入一些范例,例如使用 getter 方法而不是使用 .NET 样式属性的 java,您可能需要研究一下。但我已经制作了一个更适合您的具体情况的代码示例。
你可以替换方 block
for (int i = 0; i < 20; i++)
{
if (cdArray[i].get_upc() == UPC)
与
cdClass foundCD = cdArray.SingleOrDefault(cd => cd.get_upc() == UPC);
或者使用 Array.Find()
BrokenGlass 建议的方法..
cdClass foundCD = Array.Find(cdArray, delegate(cdClass cd) { return cd.get_upc() == UPC); });
关于c# 在对象数组中搜索特定的 int 值,然后返回该对象的所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5384549/