[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5259
  • Last Modified:

Generics Find Method ?? Predicate

Morning All...

I am using Generics to handle my list of objects.  I have never used generics before so am kinda bumbling along here!!!

I have my custom access layer to perform certain custom actions i want but have now hit a wall :(

I want to use the Find method to extract one Item from the Collection searching by id (property of my collection)
It is asking for a Predicate? I have no idea what that is or how to use it (i dont have a great understanding of delegates and have hardly used them)

collection class contructor...
public CustomDS(int id, string name, string secondaryname)
    {
        this._id = id;
        this._name = name;
        this._secondaryname = secondaryname;
    }

So my list has many of these objects and i want to do this.....
CustomDS GetSingle(int id, ref List<CustomDS> list) {
CustomDS item = list.Find(/*search by CustomDS.ID in here some how*/);
}

Can someone point me in the right direction for this?  I have had a look around and dont really understand what i am reading :(

Thanks
o
0
osiris247
Asked:
osiris247
  • 2
  • 2
1 Solution
 
AlexFMCommented:
int searchID;

CustomDS GetSingle(int id, List<CustomDS> list)
{
    searchID = id;    // keep ID in class member for using in HasID function
    CustomDS item = list.Find(HasID);
    return item;
}

// This function is called for every list element. If function returns true,
// this element is returned by Find function.
bool HasID(CustomDS c)
{
    return ( c.Id == searchID );
}
0
 
osiris247Author Commented:
Thanks Alex...worked a treat.  Now i understand what to do i can stop using the index to remove as the selectedindex property of my gridview seems a little flakey and gives 3 when there is only one row

One thing that concerns me a little.  I have DAL methods as static so my global int has to be static also.  Do you foresee any problems with this?

Now on with the Sort!

Thanks
o
0
 
AlexFMCommented:
I don't see problem, all these functions and variables can be static. For example, MSDN topic List<T>.Find has sample code which works with static functions.
0
 
osiris247Author Commented:
Thanks Alex.

Just about to open a question about the sorting my collection :(  ....please take a look if you get time.

o
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now