How do I use the Find method on a generic List collection

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tony Johansson

    How do I use the Find method on a generic List collection

    Hello!

    Assume I have the class shown below and it's stored in a generic List.
    If I want to find the Value for a specific Id how do I use the find method.
    We can assume that the generic List collection is named
    myWorkSheetRowP arameterList

    public class WorkSheetRowPar ameter
    {
    public string WorkSheetRowId {get; set};
    public string Id {get;set};l
    public string Type {get;set};
    public string Value {get;set};
    public string Disabled{get;se t};
    public string ParameterName{g et;set};
    public string ParameterDuplic ate{get;set};
    }

    //Tony
  • Marc Gravell

    #2
    Re: How do I use the Find method on a generic List collection

    You need a "predicate" - i.e. a condition to match, expressed as a
    delegate. Since you are using C# 3.0, this is simply:

    string id = "abc"; // etc
    WorkSheetRowPar ameter row =
    myWorkSheetRowP arameterList.Fi nd(
    x =x.Id == id);

    Marc


    Comment

    • Marc Gravell

      #3
      Re: How do I use the Find method on a generic List collection

      oh, I forgot - you'll need to get .Value afterwards.

      Actually, with LINQ (in .NET 3.5) you can also do:

      string id = "abc"; // etc
      string value = (from row in myWorkSheetRowP arameterList
      where row.Id == id
      select row.Value).Sing le();

      Marc

      Comment

      • Jon Skeet [C# MVP]

        #4
        Re: How do I use the Find method on a generic List collection

        Tony Johansson <t.johansson@lo gica.comwrote:
        Assume I have the class shown below and it's stored in a generic List.
        If I want to find the Value for a specific Id how do I use the find method.
        We can assume that the generic List collection is named
        myWorkSheetRowP arameterList
        >
        public class WorkSheetRowPar ameter
        {
        public string WorkSheetRowId {get; set};
        public string Id {get;set};l
        public string Type {get;set};
        public string Value {get;set};
        public string Disabled{get;se t};
        public string ParameterName{g et;set};
        public string ParameterDuplic ate{get;set};
        }
        It looks like you're using C# 3, so use a lambda expression:

        string id = // the ID you want to find.
        var found = myWorkSheetRowP arameterList.Fi nd(p =p.Id == id);
        string value = found.Value;

        --
        Jon Skeet - <skeet@pobox.co m>
        Web site: http://www.pobox.com/~skeet
        Blog: http://www.msmvps.com/jon.skeet
        C# in Depth: http://csharpindepth.com

        Comment

        Working...