4imble
4imble

Reputation: 14416

Can you eval or equivalent in linq?

If i had a list of question numbers

var questions =  new List<int> { 2, 4, 8 };

Is it possible to have a query that does something like this in linq?

var results = new List<Answer>();

foreach (var qNum in questions)
{
   results.AddRange(Answers.Where(x => eval(x.Question+qNum) == "Yes"));
}

So this would look up the answer for x.Question2, x.Question4 and x.Question8.

Addendum

Currently i am doing this:

    var questionAnswers = new List<Answer>();
var Q2 = Questions.Where (x => x.MainQ2.ToUpper() == "NO")
    .Select(x => new Answer { QuestionNumber = 2, AnswerText = x.MainTextQ2, User_Id = x.User_Id });

var Q4 = Questions.Where (x => x.MainQ4.ToUpper() == "NO")
    .Select(x => new Answer { QuestionNumber = 4, AnswerText = x.MainTextQ4, User_Id = x.User_Id });

var Q8 = Questions.Where (x => x.MainQ8.ToUpper() == "NO")
    .Select(x => new Answer { QuestionNumber = 8, AnswerText = x.MainTextQ8, User_Id = x.User_Id });

questionAnswers.AddRange(Q2);
questionAnswers.AddRange(Q4);
questionAnswers.AddRange(Q8);

questionAnswers.GroupBy (a => a.QuestionNumber).Dump();


public class Answer
{
    public int QuestionNumber {get;set;}
    public string AnswerText {get;set;}
    public string User_Id {get;set;}
}

Many thanks :)

Upvotes: 1

Views: 1521

Answers (3)

Tar
Tar

Reputation: 426

You can use Dynamic.cs AKA DynamicQuery AKA Dynamic Expression API

Using that, you can input a string in place of the where expression:

Answers.Where("Question"+qNum+"=\"Yes\"")

In the background, it will create something akin to Jon's answer, i.e. a dynamically created Expression, which should be suitable for most LINQ providers.

Upvotes: 1

Jon
Jon

Reputation: 437574

You can manually build up an expression that accesses the requisite property using the methods in Expression and pass that to Where (possibly compiling it first if results is indeed an IEnumerable instead of an IQueryable).

See it in action.

But why would you do this? Placing the values you want to access in a collection is so much better than putting them in individual properties. Perhaps you should improve the model so that this problem does not need to be solved at all?

Upvotes: 3

Jamiec
Jamiec

Reputation: 136154

Yes, but not directly!

x.Question should evaluate to an Array of Strings, (or perhaps IDictionary<int,string>) then you would be able to do:

var results = new List<Answers>();

foreach (var qNum in questions)
{
   results.AddRange(Answers.Where(x => x.Question[qNum] == "Yes"));
}

Upvotes: 0

Related Questions