1

From a string array

string[] str1={"u1-u2","u1-u2","u1-u4","u4-u1"};
string[] str2 = str1.Distinct().ToArray(); 

Distinct elements in a arry is:"u1-u2","u1-u4","u4-u1"

But i have to get distinct output like this: "u1-u2","u1-u4".

so please help me out

1
  • Why exactly does the output have to look like that? Are the pairs unordered (so x-y is always the same as y-x)? Commented Apr 18, 2014 at 9:18

2 Answers 2

2

You can do like this:

string[] output = str1.Select(s => new { Value = s, NormalizedValue = string.Join("-", s.Split('-').OrderBy(_ => _)) })
                      .GroupBy(p => p.NormalizedValue)
                      .Select(g => g.OrderBy(p => p.Value).First().Value)
                      .ToArray();
Sign up to request clarification or add additional context in comments.

Comments

1

You can convert all values to their normalized form and the call Distinct() on that:

string[] output = str1.Select(string.Join("-", s.Split('-').OrderBy(x => x)))
                      .Distinct()
                      .ToArray();

(This is based on the code from Ulugbek Umirov's answer.)

3 Comments

I did like that in first version of answer, but it causes the following problem: {"u4-u1"} => {"u1-u4"}.
If you consider u4-u1 and u1-u4 to be equal, then you also shouldn't care which one is going to be in the output. But the problem certainly isn't specified well enough to know that for sure.
Yes, but it's rather strange to see in output the value you don't have in the input.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.