使用LINQ,我怎么找到从列表中给定的属性值的对象? [英] Using LINQ, how do I find an object with a given property value from a List?
问题描述
我有一个名为问题类
。这问题
具有属性 QuestionID
和问题答案
。同时通过提问中的foreach这个 list进行遍历,我一定要找到
.QuestionID = 12
。如果我发现 .QuestionID = 12
那么我得马上值分配给 .QuestionAnswer =SomeText则会
的 .QuestionID = 14
。
我不想再重复在 .QuestionId = 12'找到
.QuestionID =再次14`。
有什么办法,我可以使用LINQ直接到 .QuestionID = 14
?
例如:
对于每个mQuestion作为问题在_mQuestions
如果mQuestion.QuestionId = 12然后
查找mQuestion.QuestionID = 14,并插入到Somtext
'mQuestion.QuestionAnswer =SomeText则会
万一
下一个
我认为你在寻找这样的事情。如果我有时间,我将它翻译成VB,但我认为你可以遵循。
如果(_mQuestions.Any(Q => q.QuestionID == 12))
{
问题question14 = _mQuestions.FirstOrDefault(Q => q.QuestionID == 14);
如果(question14!= NULL)
question14.QuestionAnswer =一些文本;
}
I have a class called Questions
. This Questions
has properties QuestionID
and QuestionAnswer
. While iterating through this List of Question
in foreach, I have to find .QuestionID = 12
. If I find .QuestionID = 12
then I have to immediately assign a value to .QuestionAnswer = "SomeText"
of .QuestionID = 14
.
I don't want iterate again inside .QuestionId = 12' to find
.QuestionID = 14` again.
Is there any way I can go directly to .QuestionID = 14
using LINQ?.
For example:
For Each mQuestion As Question In _mQuestions
If mQuestion.QuestionId = 12 Then
'Find mQuestion.QuestionID= 14 and insert Somtext to
'mQuestion.QuestionAnswer="SomeText"
End IF
Next
I think you're looking for something like this. If I have a moment, I'll translate it to VB, but I think you can follow.
if (_mQuestions.Any(q => q.QuestionID == 12))
{
Question question14 = _mQuestions.FirstOrDefault(q => q.QuestionID == 14);
if (question14 != null)
question14.QuestionAnswer = "Some Text";
}
这篇关于使用LINQ,我怎么找到从列表中给定的属性值的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!