-1

I'm making a method to define (create in memory for later use) an object with a few specific variables and another of the same object that I'll be using to compare.

For example:

public class User
{
    public int UserID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

// - The method
public bool IDontKnowWhatImDoing<T>(??) where T : class
{
}

The ?? is where I'm having the issue. I have another method as:

public ThisWorks<T>(Expression<Func<T, bool>> expression) where T : class
{
}

And I call it like:

ThisWorks<User>(u => u.UserID == 1 && u.Age >= 20);

To obtain all users where UserID is 1 and Age is equal or over 20. Now I'd like something to be able to do this or something close to this:

NoClue<User>(u => { u.UserID = 1, u.Name = "Whois" });

public void TheFunctionIWishFor<T>(??, Expression<Func<T, bool>> expression) where T : class
{
    // - The ?? part is where I want to get a T from
    // - with the specified values above (UserID 1 and "Whois" Name)
}

How can I achieve this, if possible?

Reason: I have a method that returns all T elements that matches the expression from a list/database, now I want to set/update said matching list/database with only the values I specify. Like this:

// - Setting all user's names and age whose have null as Name.
NotSureIfItsAGoodIdea<User>(u => { u.Name = "AllAsOne", u.Age = 20 }, f => f.Name == null);
Danicco
  • 1,573
  • 2
  • 23
  • 49
  • Possible dup: http://stackoverflow.com/questions/6624811/how-to-pass-anonymous-types-as-parameters – aqwert Mar 26 '17 at 22:43

2 Answers2

0

I'm not sure if I got your idea, but if what you want is to assign some values if the expression is true, you can do something like this, passing the object, the action, and the expression.

public static void TheFunctionIWishFor<T>(T user, Action<T> assignValuesToUser, Func<T, bool> expression) where T : class
{
    if (expression(user) == true)
    {
        assignValuesToUser(user);
    }
}
Jorge Guerrero
  • 323
  • 3
  • 5
-1

Lambda experssion on multiple conditions might be something like this:

I'm just giving you an example of how that might look in your case, I wrote something like, lets look your list, where Name is not null and age is different than 0 or whatever condition you would like to add there..

u => u.Lists.Include(l => l.Name)
     .Where(l => l.Name!= String.Empty && l.Age>= 0)

Multiple statements can be wrapped in braces.

See the documentation

Roxy'Pro
  • 4,216
  • 9
  • 40
  • 102
  • Not really sure how this answers the question; it's asking about how to pass an `Expression>` to a method without knowing the return type (an anonymous type). This answer just addresses *how* to write a lambda expression, which OP has already provided. – Rob Mar 26 '17 at 23:25