Distinct list<string> of chars
c#, distinct, linq, list
Solution
It looks like you want:
var distinct = list
.Select((str, idx) => new { Str = str, Idx = idx })
.GroupBy(pair => new HashSet<char>(pair.Str), HashSet<char>.CreateSetComparer())
.Select(grp => grp.OrderBy(p => p.Idx).First())
.ToList();
This will keep the first element and remove any later strings in the sequence which contains the same characters.
You can also use `Aggregate` to track the character sets you've already seen:
var distinct = list
.Aggregate(new Dictionary<HashSet<char>, string>(HashSet<char>.CreateSetComparer()), (dict, str) =>
{
var set = new HashSet<char>(str);
if (!dict.ContainsKey(set))
dict.Add(set, str);
return dict;
})
.Values
.ToList();
Problem
I have this: ``` List<string> list = new List<string>(); list.Add("a-b-c>d"); list.Add("b>c"); list.Add("f>e"); list.Add("f>e-h"); list.Add("a-d>c-b"); ``` I want to delete duplicates. In this case duplicates are "a-b-c>d" and "a-d>c-b". Both have same chars but in diferente order. I tried with: ``` list.Distinct().ToList(); ``` But didn't work!