I’m searching a list of objects for a certain property. I’m repeating this code for a lot of properties, so I’m trying to make the reading of the property as compact as possible.
Here’s what I currently have:
value = ReadValue(p => p.ProductCatalogId != 0, p => p.ProductCatalogId);
public T ReadValue<T>(Func<MyType, bool> predicate, Func<MyType, T> selector)
{
return m_settingsPages.Where(predicate).Select(selector).FirstOrDefault();
}
I always compare against the default value for the type, and always for inequality. I would like to remove the predicate argument. Can I use partial application or a similar technique to get rid of the predicate argument?
Pseudo code:
value = ReadFirstValue(p => p.ProductCatalogId);
public T ReadFirstValue<T>(Func<MyType, T> selector) where T : IEquatable<T>
{
var predicate = selectorToPredicate(selector); //Compare with default(T) for non equality
return m_settingsPages.Where(predicate).Select(selector).FirstOrDefault();
}
How would selectorToPredicate look and how would I call it?
Sounds like you could do something as simple as:
One thing to note – if your property is a string property, this will return empty strings. Is that what you want?