gpt4 book ai didi

vb.net - 比较和合并对象列表

转载 作者:行者123 更新时间:2023-12-02 04:51:06 25 4
gpt4 key购买 nike

我有一个包含许多具有此定义的对象的列表:

Public Class Helper
Public Property UserPrincipal As UserPrincipal
Public Property Groups As New List(Of String)
Public Property Server As New List(Of String)
End Class

假设,一个对象看起来像这样:

UserPrincipal.Name = Jan
Groups = {group_1, group_2, group_3}
Server = {Server1}

还有一个:

UserPrincipal.Name = Jan
Groups = {group_1, group_3}
Server = {Server2}

现在我想检查每个对象的属性“Groups”,如果一个对象的“Groups”包含另一个对象的“Groups”,则创建一个新对象。

所以新的对象列表应该是这样的:

UserPrincipal.Name = Jan
Groups = {group_1, group_2, group_3}
Server = {Server1, Server2}

这可以使用 linq 吗?

感谢和问候,简

更新:10:42:将“服务器”属性的类型从字符串更改为列表(字符串)

更新 12:04:让我试着澄清一下我的问题。任务是收集服务器本地组的成员。为此,我使用具有正确凭据的新 principalcontext 连接到每台服务器,获取正确的组(它是远程桌面用户组)并获取该组的所有成员。有了这些信息,我填写了提到的“助手”对象,其中包含用户主体(该组的成员)、组(远程桌面用户组的成员)和服务器名称。

所以我得到了 n * Helper-objects,其中 n 是服务器计数。

现在,有两个要求:比方说,我这里有两台服务器,server1server2。一切都一样,但服务器名称不同,所以我只想要一个具有属性 Server = {server1, server2} 的对象。

第二个要求与第一个要求基本相同,但是:如果 Groups 属性包含添加至少一个唯一相关性,则也执行此操作并将该组添加到列表中(如果它不在列表中)。

不知道现在是否更清楚了:)现在将展示一个简短的例子。

对象 1:
UserPrincipal.Name = Jan
组 = {域用户}
服务器 = {Server1}

对象 2:
UserPrincipal.Name = Jan
组 = {域用户}
服务器 = {Server2}

预期对象:
UserPrincipal.Name = Jan
组 = {域用户}
服务器 = {Server1, Server2}

例子2:
对象 1:
UserPrincipal.Name = Jan
组 = {域用户,测试用户}
服务器 = {Server1}

对象 2:
UserPrincipal.Name = Jan
组 = {测试用户}
服务器 = {Server2}

预期对象:
UserPrincipal.Name = Jan
组 = {域用户,测试用户}
服务器 = {Server1, Server2}

最后一个,puhh:

对象 1:
UserPrincpial.Name = Jan
组 = {测试用户}
服务器 = {Server1}

对象 2:
UserPrincipal.Name = Jan
组 = {域用户}
Server = {Server1} 或 {Server2} 等无关紧要。

预期结果:没有变化导致属性 groups 完全不同。

最佳答案

根据您更新的问题和评论,这似乎是您想要的:

Dim upGroups = From helper In helpers 
Group helper By helper.UserPrincipal Into Group
Select New Helper With {
.UserPrincipal = UserPrincipal,
.Groups = Group.SelectMany(Function(h) h.Groups).Distinct().ToList(),
.Server = Group.SelectMany(Function(h) h.Server).Distinct().ToList()
}
Dim newHelpers = upGroups.ToList()

旧答案

您可以使用 Groups.Intersect(h.Groups).Any() 来检查哪些助手包含交叉组。然后你可以使用一个循环来合并它们:

Dim query = From helper In helpers
Let group = helpers.Where(Function(h) helper.Groups.Intersect(h.Groups).Any())

Dim processed As New HashSet(Of Helper)()
Dim newHelpers As New List(Of Helper)
For Each x In query
If x.group.Any(AddressOf processed.Contains) Then
' was already processed, skip '
Continue For
End If
Dim mergedHelper = New Helper With {
.UserPrincipal = x.group.First().UserPrincipal,
.Groups = x.group.SelectMany(Function(h) h.Groups).Distinct().ToList(),
.Server = x.group.SelectMany(Function(h) h.Server).Distinct().ToList()
}
newHelpers.Add(mergedHelper)
For Each helperInGroup In x.group
processed.Add(helperInGroup)
Next
Next

关于vb.net - 比较和合并对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28295044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com