开发者

c# search an array of objects for a specific int value, then return all the data of that object

开发者 https://www.devze.com 2023-02-18 16:42 出处:网络
So i\'ve created a class that holds strings, ints, and floats. then i declared an array in main of those types and read in objects of that type into it

So i've created a class that holds strings, ints, and floats.

then i declared an array in main of those types and read in objects of that type into it

now i need to search that array for a specific value, and if that value matches, then return the whole object

how would i go about doing this?

really stumped

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: ");
        art开发者_StackOverflow中文版ist = 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;
    }

MAIN:

//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)


You could use a simple LINQ extension method to search for the object.

var foundItem = myArray.SingleOrDefault(item => item.intProperty == someValue);

Here is some MSDN information regarding LINQ to get you more familiar.

EDIT for the code posted.

I first want to say it looks like you are bringing across some paradigms from a different language, like java with your getter method instead of using .NET style properties, something you might want to look into. But I have made a code example more tailored to your specific case..

You can replace the block

for (int i = 0; i < 20; i++)
{
    if (cdArray[i].get_upc() == UPC)

With

cdClass foundCD = cdArray.SingleOrDefault(cd => cd.get_upc() == UPC);

Or using the Array.Find() method as suggested by BrokenGlass..

cdClass foundCD = Array.Find(cdArray, delegate(cdClass cd) { return cd.get_upc() == UPC); });


Array.Find() is an alternative to LINQ in this special case, especially if you are restricted to an older .NET version:

var fooItem = Array.Find(myArray, item => item.fooProperty == "bar");


Use LINQ like:

public class Car
{
    public int ID { get; set; }
    public int CarName { get; set; }
}


class Program
{
    public IEnumerable<Car> GetCars
    {
        get { return MyDb.Cars; }
    }

    static void Main(string[] args)
    {
        Car myCar = GetCars.FirstOrDefault(x => x.ID == 5);
        Console.WriteLine("ID: {0} | CarName {1}", myCar.ID, myCar.CarName);
    }
}

http://msdn.microsoft.com/en-us/library/bb397926.aspx will provide you with the necessary information to get you started with LINQ.


class TheThing {
    public int T1;
    public float T2;
}


List<TheThing> list = new List<TheThing>();

// Populate list...

var instance = (from thing in list
               where thing.T1 == 4
               select thing).SingleOrDefault();

This assumes you'll only have one match where T1 == 4, if you're going to have more than one then do something like this:

var instances = from thing in list
                where thing.T1 == 4
                select thing;


For those that are still "stuck" in .Net 2...

My class array structure...

public class EmployerContactDetailsClass
{
    public string wsStudentID { get; set;}
    public string wsOrgID { get; set;}
    public string wsContactID { get; set;}
    public string wsContactName { get; set;}
    public string wsContactEmail { get; set;}
    public string wsEmployerEmail { get; set;}
    public bool wsUserChoiceVerifier { get; set;}
}

I want to find a specific element in this class based on a passed index value using wsStudentID == 'somevalue'.

First create a list array

List<EmployerContactDetailsClass> OrgList = new List<EmployerContactDetailsClass>();

Next create a single node element

EmployerContactDetailsClass OrgElem = new EmployerContactDetailsClass();

Build your list from some data source (my case a Reader object)

                        OrgElem.wsOrgID = reader["OrganisationID"].ToString();  //Org ID from database
                        OrgElem.wsContactID = reader["ContactID"].ToString();   //Contact ID from employer database
                        OrgElem.wsUserChoiceVerifier = (bool)reader["UserChoiceVerify"];  //boolean by default
                        if (reader["ContactGivenName"].ToString() != string.Empty && OrgElem.wsUserChoiceVerifier)
                            OrgElem.wsContactName = reader["ContactGivenName"].ToString() + " " + reader["ContactFamilyName"].ToString();
                        else
                            OrgElem.wsContactName = "TO WHOM IT MAY CONCERN";
                        OrgElem.wsContactEmail = reader["ContactEmail"].ToString();   //"support@tecnq.com.au";
                        OrgElem.wsEmployerEmail = reader["OrganisationEmail"].ToString();    //"support@tecnq.com.au";

                        //now add the elements into the array class
                        OrgList.Add(OrgElem);

Convert the List<> into an Array[]

EmployerContactDetailsClass[] OrgListArray = (EmployerContactDetailsClass[])OrgList.ToArray();

Find a given StudentID in the array using a Delegate.

String wsStudentID = 'FIND007'; //with respect to Roger Moore RIP
EmployerContactDetailsClass OrgElemFound = Array.Find(OrgListArray, ByStudentID(wsStudentID));

And the Predicate method somewhere else on your code...

//predicate method to return true or f if studentID matches the array list (used to pass into SendEmail)
private Predicate<EmployerContactDetailsClass> ByStudentID(string wsStudentID)
{
    return delegate(EmployerContactDetailsClass OrgElem)
    {
        return OrgElem.wsStudentID == wsStudentID;
    };
}

Cheers!

0

精彩评论

暂无评论...
验证码 换一张
取 消