Assuming that you have
class GroupAssets
{
public String Name { get; set; }
public IList Assets { get; set; }
}
List<GroupAssets> GroupList = new List<GroupAssets>{
new GroupAssets { Name="Group1", Assets = new List<string>{ "A" ,"B", "C", "D" }},
new GroupAssets { Name="Group2", Assets = new List<string>{ "A" ,"B", "E", "F" }},
new GroupAssets { Name="Group3", Assets = new List<string>{ "A" ,"B", "H", "G" }},
new GroupAssets { Name="Group4", Assets = new List<string>{ "A" ,"I", "C", "J" }},
};
note, that each Asset
has 4 items (not 1) you can put
Code:
HashSet<string> duplicates = new HashSet<string>();
HashSet<string> all = new HashSet<string>();
foreach (var item in GroupList)
foreach (var asset in item.Assets)
if (!all.Add(asset)) // duplicate if all contains the asset
duplicates.Add(asset);
// removing duplicates from each Asset
foreach (var item in GroupList)
item.Assets.RemoveAll(item => duplicates.Contains(item));
Let's have a look:
string report = string.Join(Environment.NewLine, GroupList
.Select(item => $"{item.Name} => {string.Join(", ", item.Assets)}"));
Console.WriteLine(report);
Console.WriteLine("Duplicate => {string.Join(", ", duplicates)}");
Outcome:
Group1 => D
Group2 => E, F
Group3 => H, G
Group4 => I, J
Duplicate => A, B, C
If, however, each of Assets
contains 1 comma separated item, you should add Split
and Join
:
HashSet<string> duplicates = new HashSet<string>();
HashSet<string> all = new HashSet<string>();
foreach (var item in GroupList)
foreach (var asset in item.Assets.SelectMany(list => list.Split(',')))
if (!all.Add(asset))
duplicates.Add(asset);
foreach (var item in GroupList) {
item.Assets = item
.Assets
.Select(asset => asset.Split(',').Where(c => !duplicates.Contains(c)))
.Where(asset => asset.Any())
.Select(asset => string.Join(",", asset))
.ToList();
}