I want to have a "predicate" (it's in quotes, since I don't know the right word), that returns different fields of an object, based on conditions. I hope a short example will illustrate.
Predicate<MyClass> predicate
if (condition1)
predicate = x => x.Field1;
else if (condition2)
predicate = x => x.Field2;
foreach(vat item in ListOfItems)
{
predicate(item) = someValue;//Here I am changing the value of that field.
}
The general term you're looking for is "delegate". While you can't directly do something like predicate(item) = someValue; in C#, you can use Actions and/or Funcs to do what you're trying to do. Getting values is the more usual way of doing things, e.g. LINQ's Select could be implemented like:
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, TResult> selector
)
{
foreach (var item in source)
yield return selector(item);
}
And is used like:
myList.Select(x => x.Field1);
You could define something that can set properties, like this:
public static void SetAll<TSource, TProperty>(
this IEnumerable<TSource> source,
Action<TSource, TProperty> setter,
TProperty someValue // example for how to get the value
)
{
foreach (var item in source)
{
setter(item, someValue);
}
}
And use it like:
myList.SetAll((x, value) => x.Property1 = value, "New value");
// all Property1s are now "New value"
Or with something like your example:
Action<MyClass, string> predicate;
if (condition1)
predicate = (x, value) => x.Property1 = value;
else
predicate = (x, value) => x.Property2 = value;
foreach (var item in ListOfItems)
{
predicate(item, someValue);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With