I have a string List like this
code
List<string> MyList = new List<string>();
MyList.Add("153");
MyList.Add("112");
MyList.Add("531");
MyList.Add("675");
MyList.Add("889");
MyList.Add("351");
code
I want only one combination of (153) or (531) or (351).
The output should be
153
112
675
889
Edit:I know if I want to remove duplicate i should use MyList =MyList.Distinct();
as suggested in another duplicate Remove duplicates from a List<T> in C# of my previous (now deleted) question. but the problem is (153),(531),(351) are not duplicate.
Obviously I read documentation and it shows some alternative version of Distinct
with some sort of "comparer", but example there is for objects and I have strings.
When I asked the same question about an hour ago it was closed by ... as duplicate of https://stackoverflow.com/a/50177/477420 which clearly not applicable to me at all - I don't know why I would ever compare two strings as sequences of characters ignoring order. I still tried that code and it returned "true" for one of the cases I have:
"153".OrderBy(i => i).SequenceEqual("531".OrderBy(i => i))
Even then it does not look useful.
A quick and a bit dirty way of getting what you wanted, without custom comparer and with items in original order:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
List<string> MyList = new List<string>();
MyList.Add("153");
MyList.Add("112");
MyList.Add("531");
MyList.Add("675");
MyList.Add("889");
MyList.Add("351");
int i = 0;
var ac = new Dictionary<int, string>();
var res = new Dictionary<int, string>();
foreach (var a in MyList)
{
res.Add(i, a);
var ou = a.ToArray();
Array.Sort(ou);
ac.Add(i, new String(ou));
i++;
}
var filteredDictionary = ac.GroupBy(s => s.Value).Where(gr => gr.Any()).Select(g => g.First()).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
var ret = res.Where(x => filteredDictionary.ContainsKey(x.Key)).Select(x => x.Value);
foreach (var c in ret)
{
Console.WriteLine(c);
}
}
}
Result:
153
112
675
889
Fiddle: https://dotnetfiddle.net/#&togetherjs=1dgVkP8AGf
This does not contain any safety checks, nor does it handle strings that are not 'numbers', but will work with your example leaving first occurrence of given combination.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments