Reputation: 68
I have custom type name Netsgroup which is a collection of Net class.
Net class , contsains: Netname and list of string Parts.
class Netsgroup: CollectionBase
{
// a collection of nets
public Net[] nets
{
get { return (Net[]) this.InnerList.ToArray(typeof(Net)); }
}
}
public class Net
{
string netname;
public string Netname
{
get { return netname; }
set { netname = value; }
}
List<string> parts= new List<string>();
public List<string> Parts
{
get { return parts; }
}
}
An example of Netsgroup is:
Net1 u1, u2, u3
Net2 u4,u5,u3
Net3 u4,u6, u7
Each line is with Netname and Parts.
I want to find the duplicates in the Netsgroup collection.
Like:
net1, net2 has u3
net2, net3 has u4
How can I intersect the Parts from all Nets to find duplicates?
Thanks, Avi.
Upvotes: 1
Views: 372
Reputation: 245046
I think doing this would be easiest using LINQ:
var duplicates =
from net in netsgroup.nets
from part in net.Parts
group net by part into g
where g.Count() >= 2
select g;
If you want to write the results in the format you specified into console, you can use something like:
foreach (var dup in duplicates)
Console.WriteLine(
"{0} has {1}", string.Join(", ", dup.Select(n => n.Netname)), dup.Key);
Upvotes: 2
Reputation: 7546
IEnumerable<string> parts1 = netGroup1.nets.SelectMany(n => n.Parts);
IEnumerable<string> parts2 = netGroup2.nets.SelectMany(n => n.Parts);
IEnumerable<string> intersectedNets = Enumerable.Intersect(parts1, parts2);
Upvotes: 1