Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

arrays - Union and Intersection in PowerShell?

I have an array of objects of the following structure:

structure Disk
{
  int UID;
  String Computer;
}

A computer may have a bunch of shared disks, and a disk may be shared among computers.

I want to find out all the disks common to all the computers. For example, I have computer A, B, and C; Disks 1, 2, and 3. The disk array is {1,A}, {1,B}, {2,A},{2,B},{2,C},{3,A}. The result that I want should be the disk 2, because it appears on A, B, and C.

Is there a effective way to achieve this?

With multiple foreach loops it's achievable, but definitely I want a better way. I'm thinking about operations like intersection, but didn't find this in PowerShell.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming $arr is the array, you can do like this:

$computers = $arr | select -expand computer -unique
$arr | group uid | ?{$_.count -eq $computers.count} | select name

In general, I would approach union and intersection in Powershell like this:

$a = (1,2,3,4)
$b = (1,3,4,5)
$a + $b | select -uniq    #union
$a | ?{$b -contains $_}   #intersection

But for what you are asking, the above solution works well and not really about union and intersection in the standard definition of the terms.

Update:

I have written pslinq which provides Union-List and Intersect-List that help to achieve set union and intersection with Powershell.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...