简体   繁体   中英

Get distinct output from an array

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

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();

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 .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM