Skip to content

Instantly share code, notes, and snippets.

@AlexVallat
Created March 4, 2021 18:20
Show Gist options
  • Save AlexVallat/377cb24f1a445665a7e913017a1fe98c to your computer and use it in GitHub Desktop.
Save AlexVallat/377cb24f1a445665a7e913017a1fe98c to your computer and use it in GitHub Desktop.
MSBuild ItemGroup Intersection

It's not obvious how to produce an intersection of two itemgroups in MSBuild. There's this brainteaser solution based on tricky metadata behaviour, but it only works inside a <target> due to it's use of metadata.

There is another way. Algebra tells us that A ∩ B = A ∖ (A∖B): intersection of A and B is A excluding (A excluding B). This can be expressed in MSBuild as:

<ItemGroup>
	<A Include="1" />
	<A Include="2" />
	<A Include="3" />
</ItemGroup>
<ItemGroup>
	<B Include="2" />
	<B Include="3" />
	<B Include="4" />
</ItemGroup>
<ItemGroup>
	<A_not_B Include="@(A)" Exclude="@(B)" />
	<A_intersect_B Include="@(A)" Exclude="@(A_not_B)" />
</ItemGroup>

<Message Text="A∩B: @(A_intersect_B)"/>: A∩B: 2;3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment