我有一个名为Questions
的班级。此Questions
具有属性QuestionID
和QuestionAnswer
。在foreach中迭代这个List of Question
时,我必须找到.QuestionID = 12
。如果我找到.QuestionID = 12
,那么我必须立即为.QuestionAnswer = "SomeText"
的{{1}}分配一个值。
我不想再在.QuestionID = 14
内再次迭代。再次问题ID = 14`
有什么方法可以直接使用LINQ直接转到.QuestionId = 12' to find
。
例如:
.QuestionID = 14
答案 0 :(得分:21)
我认为你正在寻找这样的东西。如果我有时间,我会将其翻译成VB,但我认为你可以关注。
if (_mQuestions.Any(q => q.QuestionID == 12))
{
Question question14 = _mQuestions.FirstOrDefault(q => q.QuestionID == 14);
if (question14 != null)
question14.QuestionAnswer = "Some Text";
}
答案 1 :(得分:1)
很遗憾,您的数据结构(List
)要求您在找到Question-14
后再次搜索以查找Question-12
。如果您的Question
列表按ID排序,则可以进行一些改进,但一般情况下,只有了解List
或Array
,才能直接访问Dictionary
或IDictionary<Question> questions = _mQuestions.ToDictionary(q => q.id);
的元素。元素属性的值。
适用于您的问题的数据结构是Question
,因为它允许通过某些值索引对象,以及有效直接访问这些对象,而无需遍历整个集合。
您可以使用Linq通过调用ToDictionary()扩展程序将列表转换为字典:
if (questions.ContainsKey(12) && questions.ContainsKey(14))
{
questions[14].QuestionAnswer = "Some Text";
}
这使用ContainsKey
对象的ID作为键,对象作为值。然后在您的代码中,您可以执行以下操作:
{{1}}
请注意{{1}}和索引器(operator [])都在常量时间内执行。
答案 2 :(得分:0)
请注意,我对它的看法比其他样本更加冗长,但我设法做的只有LINQ。 (注意下面的C风格评论!)
Private Shared Sub Main(args As String())
Dim questions As List(Of Question) = GetQuestions()
Dim question As Question = ( _
Where q.ID = 14 AndAlso _
questions.Exists(Function(p) p.ID = 12)).FirstOrDefault()
If question IsNot Nothing Then
question.Answer = "Some Text"
End If
End Sub
// Build the collection of questions! We keep this simple.
Private Shared Function GetQuestions() As List(Of Question)
Dim questions As New List(Of Question)()
questions.Add(New Question(12, "foo"))
questions.Add(New Question(14, "bar"))
Return questions
End Function
// You've already got this class. This one is just my version.
Public Class Question
Public Sub New(id As Integer, answer As String)
Me.ID = id
Me.Answer = answer
End Sub
Public Property ID() As Integer
Get
Return m_ID
End Get
Set
m_ID = Value
End Set
End Property
Private m_ID As Integer
Public Property Answer() As String
Get
Return m_Answer
End Get
Set
m_Answer = Value
End Set
End Property
Private m_Answer As String
End Class
答案 3 :(得分:0)
使用LINQ:
var listOfQ = new List<Question>();
// populate the list of Question somehow...
var q14 = listOfQ.FirstOrDefault(q => q.QuestionID == 14);
if (listOfQ.Any(q => q.QuestionID == 12) && q14 != null)
{
q14.QuestionAnswer = "SomeText";
}