List Predicate delegates: How cool is that?
Posted: Fri Nov 14, 2008 4:12 pm
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:
so I can determine the value of a Product's "Content Type" template thus:
Nice. 
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,
...
}
Code: Select all
string mytype = product.TemplateFields.Count > 0 ?
product.TemplateFields.Find(delegate(ProductTemplateField t)
{ return (ItemTemplateType)t.InputFieldId == ItemTemplateType.ContentType; }).InputValue ?? "" : "";
