【问题标题】:Linq query not including items contained in list (of class)Linq 查询不包括列表中包含的项目(类)
【发布时间】:2014-11-11 09:24:55
【问题描述】:

我在处理这个 Linq 查询时遇到了问题。我有一个包含我要处理的所有数据的数据表(包括一个名称列)。我想对此数据表进行 Linq 查询,但我想排除在 myNegativeList 中也可以找到数量 >= 15 的名称。

myNegativeList 有 (Name = "John"; Amount = 5) John 不应从 Linq 查询中排除。 myNegativeList 也有 (Name = "Sally"; Amount = 100) Sally 应从 Linq 查询中排除

Class ListItems
    Public Name As String
    Public Amount As Decimal
End Class

Sub GetList()

    'get data table
    Dim NoticeTable As DataTable = GetTable 'has Name and other data

    'get my list of names I don't want
    Dim myNegativeList As List(Of ListItems) = getMyList

    'Psuedo code here 
    Dim Cust = From Notice In NoticeTable _
               Where Notice.Name not in (Select Name from myList where Amount >= 15)

End Sub

如何进行不包括名称的 Linq 查询(存在于 myNegativeList AND amount >= 15)

【问题讨论】:

  • 尽量不要在查询中使用“not”运算符
  • @SantoshaEpili 你应该not不要在VB中使用“not”运算符:)

标签: vb.net linq


【解决方案1】:

尝试这样做:

Dim Cust  = From row In NoticeTable.AsEnumerable() _ 
           Let name = row.Field(Of String)("Name") _ 
           Where Not myNegativeList.Where(Function(c) c.Amount >= 15 ) _ 
                                   .Any(Function(c) c.Name = name) _
           Select row

查看here 了解如何使用 DataTable 执行 Linq 的另一个示例

【讨论】:

  • 谢谢,我明天看看。
【解决方案2】:

试试这个:-

Dim result = From dr In NoticeTable.Rows
                 Where Not myNegativeList.Any(Function(x) x.Amount >= 15 AndAlso x.Name = dr("Name"))
                 Select dr("Name")

我不知道为什么 .Net Fiddle 不支持 DataTable,但你可以复制我从 Here 尝试过的代码。

【讨论】:

  • 如果我没记错的话,Linq 联接是一个内部联接,它会将我的大部分数据记录从数据表中排除。只有少数出现在 myNegativeList 中。
  • @D_Bester - 是的,我误解了你的问题!我以为您只想过滤那些出现在负面列表中的数据表中的名称,无论如何已经更新了代码。请检查,您可以检查我在 Fiddle 中使用的示例数据。
  • 这太棒了!我使用Select dr 而不是Select dr("Name"),因为我实际上想要整个数据行。非常感谢。
  • 我检查了你的小提琴并看到错误消息要求引用System.XML。我添加了它,错误消失了。
  • @D_Bester - 好的,谢谢!在 .Net DataTable 中感到困惑 cz 存在于 System.Data 命名空间中。
猜你喜欢
  • 1970-01-01
  • 2014-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-01
相关资源
最近更新 更多