0

Below linq query gives two entries of the same items in nd. Looking for a way to remove the reversed entry.

//unit = new List<string>{"F1","F2","F3","F4","F5","F6","F7","F8","F9"}
//v["F3"]="12" v["F6"]="12"

var nd = (from n1 in unit 
          from n2 in unit
          where n1 != n2 && v[n1].Length == 2 && v[n1] == v[n2]
          select new {n1,n2}).ToList();

The values in nd is given as below. How can i avoid the 2nd entry?

Count = 2
    [0]: { n1 = "F3", n2 = "F6" }
    [1]: { n1 = "F6", n2 = "F3" }
har07
  • 88,338
  • 12
  • 84
  • 137

3 Answers3

1

The solution is extremely trivial. Instead of checking that the two entries are different, check if one is strictly greater than the other:

var nd = (from n1 in unit 
          from n2 in unit
          where n1 > n2 && v[n1].Length == 2 && v[n1] == v[n2]
          select new {n1,n2}).ToList();
Blindy
  • 65,249
  • 10
  • 91
  • 131
0

You could select (n1, n2, min(n1, n2), max(n1, n2)), group by the min and max and select the first in each group.

var result = nd.GroupBy(item => new {item.min, item.max}).Select(grp => new {grp.First().n1, grp.First().n2});

Alioza
  • 1,690
  • 12
  • 14
-1

You can compare if one is less than or greater than the other instead of just checking for inequality. The trick is well-known in SQL, for example : 1, 2.

In .NET LINQ implementation, you can use String.CompareOrdinal() method since comparing strings can't be as straightforward as using < or > operator :

var nd = (from n1 in unit
          from n2 in unit
          where String.CompareOrdinal(n1,n2) < 0 && v[n1].Length == 2 && v[n1] == v[n2]
          select new { n1, n2 }).ToList();
Community
  • 1
  • 1
har07
  • 88,338
  • 12
  • 84
  • 137