Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Something very similar to predicate, but not a predicate

Tags:

c#

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.
}
like image 872
Anarion Avatar asked Dec 01 '25 05:12

Anarion


1 Answers

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);
}
like image 103
Tim S. Avatar answered Dec 03 '25 17:12

Tim S.