linq 根据对象属性从列表中选择对象

jdzmm42g  于 2022-12-15  发布在  其他
关注(0)|答案(8)|浏览(204)

我有一个物品清单

class Answer
{
   bool correct;
}

List<Answer> Answers = new List<Answer>();

在linq中有没有一种方法可以让我根据对象的属性来选择它?
到目前为止我有

Answer answer = Answers.Single(a => a == a.Correct);

但它不起作用

3yhwsihp

3yhwsihp1#

首先,如果有多个元素满足条件,Single将抛出异常;其次,您的条件应该只检查Correct属性是否为true;现在,您正在检查a是否等于a.Correct(甚至不会编译)。
你也可以考虑使用First(如果没有这样的元素,它会抛出),或者FirstOrDefault(如果没有这样的元素,它会返回null作为引用类型),或者Where后跟ToList(它会返回满足条件的所有元素):

// this will either find a single correct answer,
// or throw an exception if there are no correct answers
// or if there is more than one correct answer
var correct = answers.Single(a => a.Correct);

// this will either find a single correct answer,
// or return null if there are no correct answers,
// or throw an exception if there is more than one correct answer
var correct = answers.SingleOrDefault(a => a.Correct);

// this will return the first correct answer,
// or throw an exception if there are no correct answers
var correct = answers.First(a => a.Correct); 

// this will return the first correct answer, 
// or null if there are no correct answers
var correct = answers.FirstOrDefault(a => a.Correct); 

// this will return a list containing all answers which are correct,
// or an empty list if there are no correct answers
var allCorrect = answers.Where(a => a.Correct).ToList();
9cbw7uwe

9cbw7uwe2#

我假设你得到一个异常是因为Single,你的列表可能有不止一个答案被标记为正确,这就是为什么Single会抛出一个异常使用First,或FirstOrDefault();

Answer answer = Answers.FirstOrDefault(a => a.Correct);

此外,如果你想获得所有项目的列表标记为正确的,你可以尝试:

List<Answer> correctedAnswers =  Answers.Where(a => a.Correct).ToList();

如果您想要的结果是Single,那么您在查询中所犯的错误就是将一个项与bool值进行比较。

a == a.Correct

语句中的错误,您的单查询应该是:

Answer answer = Answers.Single(a => a.Correct == true);


或简称为:

Answer answer = Answers.Single(a => a.Correct);
fivyi3re

fivyi3re3#

你的表达式永远不会求值。
您正在将aa的属性进行比较。
a的类型是Answer。a.Correct,我猜是一个布尔值。
长格式:-

Answer = answer.SingleOrDefault(a => a.Correct == true);

简称:-

Answer = answer.SingleOrDefault(a => a.Correct);
oxalkeyp

oxalkeyp4#

如果a.Correct是正确答案的bool标志,则需要。

Answer answer = Answers.Single(a => a.Correct);
px9o7tmv

px9o7tmv5#

我想你是在找这个吧?

var correctAnswer = Answers.First(a => a.Correct);

您可以通过键入以下内容来使用single:

var correctAnswer = Answers.Single(a => a.Correct);
zfciruhq

zfciruhq6#

当然可以!
使用FirstOrDefault()选择符合条件的第一个对象:

Answer answer = Answers.FirstOrDefault(a => a.Correct);

否则,使用Where()选择列表的子集:

var answers = Answers.Where(a => a.Correct);
fykwrbwg

fykwrbwg7#

这里有几件事需要解决:
1.类声明中没有括号
1.将“正确”的属性设置为公共属性
1.然后进行选择
您的代码将如下所示

List<Answer> answers = new List<Answer>();
/* test
answers.Add(new Answer() { correct = false });
answers.Add(new Answer() { correct = true });
answers.Add(new Answer() { correct = false });
*/
Answer answer = answers.Single(a => a.correct == true);

而这门课

class Answer
{
   public bool correct;
}
68de4m5k

68de4m5k8#

Answers = Answers.GroupBy(a => a.id).Select(x => x.First());

这将通过电子邮件选择每个唯一对象

相关问题