【问题标题】:Inner join in collections using LINQ使用 LINQ 内部加入集合
【发布时间】:2013-08-12 12:36:15
【问题描述】:

我有两个集合,我必须进行连接才能获得一个值,但是当我尝试它时抛出错误。

//代码:

 Dim ExclusiveComment As ExclusiveComments = Nothing

ExclusiveComment = From ExclusiveCommentLinq In Me.ExclusiveCommentsCollection
                   Join ExistingCommentsLinq In Me.CombinedExclusiveCommentsCollection On      ExclusiveCommentLinq.CommentDescription Equals ExistingCommentsLinq(0)
                   Select ExclusiveCommentLinq

在上面的代码中,

ExclusiveCommentsCollection= 类的集合(ExclusiveComments) CombinedExclusiveCommentsCollection = 常规字符串集合(单列)

两个集合都有共同的列“CommentDescription”,我需要使用它从ExclusiveCommentsCollection获取值。

你能告诉我我错在哪里以及如何做到这一点吗?

错误:

Option strict on 不允许从 'System.collections.generic.ienumarable(Of ExclusiveComments 到 ExclusiveComments) 的隐式转换

【问题讨论】:

    标签: .net vb.net linq collections


    【解决方案1】:

    问题是连接总是会产生一个对象的“列表”,即使该列表只包含一个对象。在这种情况下,您只需要在末尾使用“FirstOrDefault”来限定您的查询,以表明您只想使用一个结果。

    Dim ExclusiveComment As ExclusiveComments = Nothing
    ExclusiveComment = (From ExclusiveCommentLinq In Me.ExclusiveCommentsCollection
                       Join ExistingCommentsLinq In Me.CombinedExclusiveCommentsCollection On      ExclusiveCommentLinq.CommentDescription Equals ExistingCommentsLinq(0)
                       Select ExclusiveCommentLinq).FirstOrDefault
    

    【讨论】:

    • 它现在给我“索引超出范围数组”错误。如何给字符串集合?在查询中。
    • 我认为“ExistingCommentsLinq(0)”是问题所在。您是说您希望 ExclusiveCommentLinq.CommentDescription 等于 ExistingCommentsLinq 中的第一项。如果是这种情况,请使用在 Linq 之外定义的单独变量。
    • 不,我想在整个集合中搜索并返回结果。我该怎么做?
    • 假设 Me.CombinedExclusiveCommentsCollection 被定义为 List(Of String) 或其他一些集合 (Of String),您可以只使用 ExistingCommentsLinq 而不是 ExistingCommentsLinq(0)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 2010-12-03
    • 2017-06-23
    • 1970-01-01
    • 2010-12-04
    相关资源
    最近更新 更多