Home > Software engineering >  c# remove duplicates for custom list
c# remove duplicates for custom list

Time:10-16

Hello I have one string like

BRC CORP---BRC SME,BRC SME---BRC CORP,Confirmation of Customer Contact,Confirmation of Suitability Check,Consent,Driver's License---National Id Card,National Id Card---Driver's License,Residence certificate

now I need to convert this to list below.

using System.Collections.Generic;
using System.Linq;

try
{
    string  mondantory_docs=Batch.Properties.Get("MissingDocCheck");
    List<string> result = mondantory_docs.Split(',').ToList();

}
catch
{
}

But I have one problem that I cant find a way. BRC CORP---BRC SME and BRC SME---BRC CORP are normally same. so I need to remove one of them from list. as result I want below.

BRC CORP---BRC SME,Confirmation of Customer Contact,Confirmation of Suitability Check,Consent,Driver's License---National Id Card,Residence certificate 

How can I remove this kind of duplicate from list

Thanks

Kind Regards

CodePudding user response:

After splitting the string, instead adding it to a list, add it to a HashSet. Then convert it to list. This should remove duplicates.

CodePudding user response:

There are bound to be many ways to do this, so I fully expect a range of answers here..

How about we zip through the list, and for any that have "---" inside, we split on "---", sort the bits we get and restore it, Then we can just get the distinct bits

string  mondantory_docs=Batch.Properties.Get("MissingDocCheck");
var result = mondantory_docs.Split(',');

var unique = result
  .Select(s => s.Contains("---") ? string.Join("---", s.Split("---").OrderBy(x=>x)) : s)
  .Distinct()
  .ToList()

(Answering based off a sole example is tricky; post more examples if you have them)

CodePudding user response:

You can use MoreLinq Nuget Package and use IEnumerable.DistinctBy(str => str).

This method will return a list of unique objects, For Example:

var list = new List<String>{"AB","BC","CB","AB","BA","BC","CB","AB" };
var distinctObjects = list.DistinctBy(ch => ch).ToList();

The distinctObjects will contain 4 objects: {AB, BC, CB, BA}.

CodePudding user response:

One simple way could be to loop through the elements and maintain a dictionary to restrict duplicates. Check if any string contains --- and any of the pair value is present in our dictionary,if yes skip the string from our unique list otherwise add the pair to dictionary. By pair, I mean A---B is pair(A,B).

Code will go like this -

List<string> result = mondantory_docs.Split(",").ToList();
Dictionary<string, string> dict = new();
List<string> unique = new();
foreach (var doc in result)
{
    if (doc.Contains("---"))
    {
        var pair = doc.Split("---").ToList();
        if (dict.ContainsKey(pair[0]) || dict.ContainsKey(pair[1]))
            continue;
        else
            dict.Add(pair[0], pair[1]);
    }
    unique.Add(doc);
}
  •  Tags:  
  • c#
  • Related