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
var fruit = ListOfFruits. FirstOrDefault(x => x.Name == "Apple"); if (fruit != null) { return fruit.ID; } return 0; This is not the only road to Rome, you can also use Single(), SingleOrDefault() or First().
The term "LINQ to Objects" refers to the use of LINQ queries with any IEnumerable or IEnumerable<T> collection directly, without the use of an intermediate LINQ provider or API such as LINQ to SQL or LINQ to XML. You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>.
Using LINQLINQ features can be used in a C# program by importing the System.
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";
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With