Page 1 of 1

List Predicate delegates: How cool is that?

Posted: Fri Nov 14, 2008 4:12 pm
by nickc
I'm sure this is nothing new to you veteran C#'pers, but I just stumbled on this solution today and it's very useful - thought I'd share...

I needed to get a value from a specific Product Item Template Field and act on it.
In the past, I'd have used a foreach loop on the Product.TemplateFields collection, tested the appropriate value on each pass, etc.

Well, any collection or list in C# should implement a Find(Predicate<T>) method that returns T, and the Predicate argument can be passed a delegate function - so a single statement can return the value I seek!

I have an enum in a static class that helps me nail down what each TemplateField does:

Code: Select all

        public enum ItemTemplateType : int
        {
            ProfileType = 31,
            ContentType = 18,
            AudienceType = 19,
            ProductFamilyType = 20,
            ...
        }
so I can determine the value of a Product's "Content Type" template thus:

Code: Select all

        string mytype = product.TemplateFields.Count > 0 ? 
                product.TemplateFields.Find(delegate(ProductTemplateField t) 
               { return (ItemTemplateType)t.InputFieldId == ItemTemplateType.ContentType; }).InputValue ?? "" : "";
Nice. :)

Re: List Predicate delegates: How cool is that?

Posted: Fri Nov 14, 2008 5:17 pm
by jmestep
That might be just what I was needing for an order item list. I had seen there was a Predicate, but hadn't figured out how it worked, so this helps.