gpt4 book ai didi

c# - 你能在 linq 中评估或等效吗?

转载 作者:太空宇宙 更新时间:2023-11-03 21:55:32 24 4
gpt4 key购买 nike

如果我有一个问题编号列表

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

是否可以在 linq 中使用查询来执行类似的操作?

var results = new List<Answer>();

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

因此这将查找 x.Question2、x.Question4 和 x.Question8 的答案。

附录

目前我正在这样做:

    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;}
}

非常感谢:)

最佳答案

可以使用 Expression 中的方法手动构建一个访问必需属性的表达式并将其传递给 Where(如果结果确实是一个,可能首先编译它IEnumerable 而不是 IQueryable)。

See it in action .

但是为什么你会这样做?将要访问的值放在集合中比将它们放在单独的属性中要好得多。或许你应该改进模型,让这个问题根本不需要解决?

关于c# - 你能在 linq 中评估或等效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12475870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com