所以我创建了一个包含字符串,整数和浮点数的类.
然后我在这些类型的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;
}
Run Code Online (Sandbox Code Playgroud)
主要:
//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)
Run Code Online (Sandbox Code Playgroud)
Qui*_*son 16
您可以使用简单的LINQ扩展方法来搜索对象.
var foundItem = myArray.SingleOrDefault(item => item.intProperty == someValue);
Run Code Online (Sandbox Code Playgroud)
这里有一些关于LINQ的MSDN信息让你更熟悉.
编辑发布的代码.
我首先要说的是,你看起来像是从一个不同的语言中引入了一些范例,比如使用getter方法的java而不是使用.NET样式属性,这是你可能想要研究的东西.但我已经根据您的具体情况制作了一个更适合的代码示例.
你可以更换块
for (int i = 0; i < 20; i++)
{
if (cdArray[i].get_upc() == UPC)
Run Code Online (Sandbox Code Playgroud)
同
cdClass foundCD = cdArray.SingleOrDefault(cd => cd.get_upc() == UPC);
Run Code Online (Sandbox Code Playgroud)
或者使用Array.Find()BrokenGlass建议的方法..
cdClass foundCD = Array.Find(cdArray, delegate(cdClass cd) { return cd.get_upc() == UPC); });
Run Code Online (Sandbox Code Playgroud)
Array.Find() 在这种特殊情况下,它是LINQ的替代品,特别是如果您被限制为较旧的.NET版本:
var fooItem = Array.Find(myArray, item => item.fooProperty == "bar");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37188 次 |
| 最近记录: |