简体   繁体   English

使用LINQ,如何从List中找到具有给定属性值的对象?

[英]Using LINQ, how do I find an object with a given property value from a List?

I have a class called Questions . 我有一个名为Questions的课程。 This Questions has properties QuestionID and QuestionAnswer . 这个Questions有属性QuestionIDQuestionAnswer While iterating through this List of Question in foreach, I have to find .QuestionID = 12 . 在foreach中迭代这个List of Question ,我必须找到.QuestionID = 12 If I find .QuestionID = 12 then I have to immediately assign a value to .QuestionAnswer = "SomeText" of .QuestionID = 14 . 如果我找到.QuestionID = 12那么我必须立即为.QuestionAnswer = "SomeText" .QuestionID = 14 .QuestionAnswer = "SomeText"赋值。

I don't want iterate again inside .QuestionId = 12' to find .QuestionID = 14` again. 我不想再次在.QuestionId = 12' to find内再次迭代以再次.QuestionId = 12' to find .QuestionID = 14`。

Is there any way I can go directly to .QuestionID = 14 using LINQ?. 有什么方法可以直接使用LINQ?来使用.QuestionID = 14

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. 如果我有片刻,我会将其翻译成VB,但我认为你可以关注。

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. 不幸的是,您的数据结构( List )要求您在找到Question-14 Question-12再次搜索以查找Question-14 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. 如果您的Question列表按ID排序,则可以进行一些改进,但一般情况下,只能通过了解元素属性的值来直接访问ListArray的元素。

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. 适用于您的问题的数据结构是Dictionary因为它允许通过某些值索引对象,以及有效直接访问这些对象而无需遍历整个集合。

You can covert your list to a dictionary using Linq by calling the ToDictionary() extension method: 您可以通过调用ToDictionary()扩展方法将您的列表转换为使用Linq的字典:

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. 它使用Question对象的ID作为键,将对象作为值。 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. 请注意, ContainsKey和索引器(operator [])都在恒定时间内执行。

Mind you, my take on it is a bit more wordy than the other samples, but I managed to do it with nothing but LINQ. 请注意,我对它的看法比其他样本更加冗长,但我设法做的只有LINQ。 (Watch out for the C-style comments below!) (注意下面的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

Using LINQ: 使用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";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 给定属性名称是动态的,如何使用linq将动态对象列表分组? - How do i group a list of dynamic objects using linq given that the property names are dynamic? LINQ:如何使用LINQ查找Array属性包含特定值的所有对象 - LINQ: How do I find all the objects whose Array property contains a particular value using LINQ 使用 LINQ,其中一个 object 属性的值为 x,我如何在不同的属性中返回该值 - Using LINQ, where one object property has a value of x, how do I return the value in a different property 如何使用Linq在列表中找到属性值不同的第一项? - How can I find the first items in a list with a different value for a property using Linq? 从列表中查找属性值 <Postavke> ()与linq - find property value from List<Postavke>() with linq 在列表中查找具有给定属性值的对象,然后查找字典值 - Find object in list with given property value then find dictionary value 如何使用LINQ从另一个列表中填充对象的属性 - How to fill a property of an object from another list using LINQ 如何使用 LINQ 在列表中找到最大值? - How can I find the maximum value in a List using LINQ? 如何从列表中获得对象的属性与某个值匹配的对象? - How do I get an object from a list where a property of that object matches a certain value? 我如何有条件地更新列表<Object>使用 LINQ 的项目 - How do I conditionally update List<Object> items using LINQ
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM