Visual Basic LINQ
问题描述:
我有两个文件,一个参*谁退休和完整的参*之一。我需要从完整名单中删除退休的参*。我正在使用LINQ来处理这个问题,因为我不能像我期望的那样工作。我试图将一个查询与另一个查询进行比较,只将参*从当前名单中退出,然后将他们添加到新文件中。但是当我打开新文件时,它并没有删除退休的参*。这里是我的代码感谢提前任何帮助。Visual Basic LINQ
' Query for retired senators
Dim senateRetiered = From line In retieredSen
Let data = line.Split(","c)
Let retName = data(0)
Select retName
' query length
Dim index As Integer = senateRetiered.ToArray.Length
' Add one to our index we will remove it later in our next query
index += 1
' Query for or 110th senate compare to our other query and only select senators that have not retiered
Dim senate110Query = From line In senate110
Let data = line.Split(","c)
Let name = data(0)
Let state = data(1)
Let party = data(2)
Where name <> senateRetiered(index - 1)
Select line
' Write the remaining sentators to a new file
IO.File.WriteAllLines("sortedSentate.txt", senate110Query)
答
我不知道我真正理解你的问题,但我认为第二个查询应该看起来更像是:
Dim senate110Query = From line In senate110
Let data = line.Split(","c)
Let name = data(0)
Let state = data(1)
Let party = data(2)
Where Not senateRetired.Any(Function(r) r.Name = name)
Select line
答
我有一个替代的解决方案是较为复杂;然而,它使参*成为阶级。如果你需要做的除了文件创建参*一些其他的工作,它可能是有用的
Class Senator
Public Name As String
Public State As String
Public Party As String
Public Overrides Function Equals(ByVal obj As Object) As Boolean
Dim other = TryCast(obj, Senator)
If other Is Nothing Then
Return False
End If
Return Name.Equals(other.Name)
End Function
Public Overrides Function ToString() As String
Return String.Format("{0},{1},{2}", Name, State, Party)
End Function
End Class
有了这个声明,你可以做到这一点
Dim senateRetiered = From line In retieredSen _
Let data = line.Split(","c) _
Select New Senator() With {.Name = data(0)}
Dim senate110Query = From line In senate110 _
Let data = line.Split(","c) _
Select New Senator() With {.Name = data(0), .State = data(1), .Party = data(2)}
Dim nonRetired = senate110Query.Except(senateRetiered)
Dim nonRetiredString = nonRetired _
.Select(Function(sen) sen.ToString())
'Note: I have to append a ".ToArray()" with .NET 3.5
IO.File.WriteAllLines("sortedSentate.txt", nonRetiredString)
这个工作我在那里发言是错误的。谢谢! – amedeiros 2012-03-31 16:51:12
您可以放弃'Let state = data(1)'和'Let party = data(2)',因为它们没有被使用。 'senateRetired'返回字符串,因此条件应该是'Not senateRetired.Any(Function(n)n = name)' – 2012-03-31 17:07:07