Using LINQ, how do I find an object with a given property value from a List?
Solution 1
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";
}
Solution 2
Unfortunately, your data structure (List
) requires that you search again to find Question-14
once Question-12
is found. If your Question
list is sorted by ID, then some improvements can be made, but in general, there is no way to directly access an element of a List
or Array
by only knowing the values of the element's property.
The data structure that is applicable to your problem is Dictionary
as it allows indexing of objects via some value, as well as efficient direct-access to those objects without the need to iterate through the entire collection.
You can covert your list to a dictionary using Linq by calling the ToDictionary() extension method:
IDictionary<Question> questions = _mQuestions.ToDictionary(q => q.id);
This uses the ID of the Question
object as the key, and the object as the value. Then in your code, you can do the following:
if (questions.ContainsKey(12) && questions.ContainsKey(14))
{
questions[14].QuestionAnswer = "Some Text";
}
Note that ContainsKey
and the indexer (operator[]) both execute in constant time.
James123
Updated on October 11, 2020Comments
-
James123 over 3 years
I have a class called
Questions
. ThisQuestions
has propertiesQuestionID
andQuestionAnswer
. While iterating through thisList 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
-
Dave Markle over 13 yearsPlease don't encourage people by translating perfectly good code to VB. :)
-
Stephan Møller almost 11 yearsNice solution! Note that you have to ensure, that ID is unique in this case, or .ToDictionary() will fail.
-
Michael Paulukonis about 9 yearsCould be worse, I just stared at a recently-coded VB.net app that was written in a VB6 idiom. <facepalm>
-
BenKoshy almost 7 years@MichaelPaulukonis the only solution is suicide
-
michael g over 6 yearstry VBA for Microsoft Applications. another p.i.n.t.a. vb subset.