【问题标题】:LINQ query to filter items inside a list of listLINQ 查询以过滤列表列表中的项目
【发布时间】:2015-05-30 06:08:21
【问题描述】:

我有一个项目列表,其中包含更多项目 ICollection,我想知道是否有人可以帮助我使用 lambda 表达式来过滤此列表。

我的列表如下所示:

Public Class ItemDto
    Public Property ItemId As Integer
    Public Property ItemLs As ICollection(Of ItemLDto) = New HashSet(Of ItemLDto)
End Class

快速浏览一下对象的外观

ItemID = 1
     ItemLs (Id=1, Type=2)
     ItemLs (Id=2, Type=3)
ItemID = 2
    ItemLs (Id=1, Type=2)
    ItemLs (Id=2, Type=3)
ItemID = 3
    ItemLs (Id=1, Type=2)
    ItemLs (Id=2, Type=3)`

我想要做的是创建一个 LINQ 查询,它将返回以下结果。基本上用Type=3 过滤掉所有ItemLs。我不知道为什么这让我感到困惑,因为它似乎应该如此简单

ItemID = 1  
    ItemLs (Id=2, Type=3)
ItemID = 2
    ItemLs (Id=2, Type=3)
ItemID = 3
    ItemLs (Id=2, Type=3)

试图避免将其放入循环并创建一个新对象,但目前我使用这个不理想的查询循环遍历它。

item.ItemsLs.FirstOrDefault(Function(m) m.Type = 3)

感谢您的指点

【问题讨论】:

    标签: .net vb.net linq


    【解决方案1】:

    SelectMany 是我认为您正在寻找的东西,使用基于语法的查询更容易推理:

    Dim result = From parent In source
                 From child In parent.ItemsLs
                 Where child.Type = 3
                 Select New With { .ItemDto = parent, .ItemLs = child  }
    

    如果有多个带有childchild 项目,它也可以工作。

    【讨论】:

    • 很抱歉回复晚了,但您帮助我更进一步。我现在得到的结果如下。我会继续修改它,看看我是否能得到结果。 ItemID = 1 ItemLs (Id=1, Type=2) ItemLs (Id=2, Type=3) ItemsLs (itemID =1 的正确信息) ItemID = 2 ItemLs (Id=1, Type=2) ItemLs (Id=2 , Type=3) ItemsLs(itemID =2 的正确信息)
    猜你喜欢
    • 2013-08-15
    • 2017-06-29
    • 1970-01-01
    • 2022-01-04
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    相关资源
    最近更新 更多