0

What method is correct if I wanted to use a variable in place of a model field attribute when searching a table?

var Variable = "name" //person has a name field
IEnumerable<person> person= db.person;
if (person.Any(item => item.Variable== "Bob"))
{
// do Stuff
}

What I am trying to do is use an ajax call on a form input field to check if it exists when input is detected, the ajax call will send through the input value and the name of the field.

I am trying to write the controller method in such a way that it is able to take 2 parameters and is reusable on all the form fields.

tama
  • 315
  • 2
  • 14
  • This is a good use case for a [lambda expression](http://www.dotnetperls.com/lambda). You'll need to know the thing you want to look for at design time, but runtime (which would be what [reflection](https://msdn.microsoft.com/en-us/library/ms173183.aspx) is for, but that shouldn't be overused because it's slow and might indicate a poor design). – mason Feb 19 '15 at 02:15
  • If this question is about refactor rather than a code problem I recommend using [Code Review StackExchange](http://codereview.stackexchange.com/). – Dustin Kingen Feb 19 '15 at 02:34

2 Answers2

0

C# does not have support for variable members.

There are alternatives.

The most straightforward solutions are to use an if/switch statement, PredicateBuilder, or the DynamicLinq library (available on nuget).

If all those fall short then you will need to build the expression trees manually.

var useName = true;

if(useName && db.person.Any(item => item.name == "Bob")
{
    // do stuff
}
Community
  • 1
  • 1
Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
-1

I think you should change the person to item note that person is the name of your collection.

var Variable = "name" //person has a name field
IEnumerable<person> person= db.person;
if (person.Any(item => item.Variable== "Bob"))
{
// do Stuff
}
Ivandro Jao
  • 2,731
  • 5
  • 24
  • 23