1

I'm trying to remove example duplicate entries from this 2D List.

I've already tried using the .Distinct().ToList() method as highlighted in answers for 1D Lists but it doesn't seem to work for me here.

My code so far:

List<List<float>> xyvertices = new List<List<float>>();
xyvertices.Add(new List<float>());
yvertices[0].Add(2);
xyvertices[0].Add(4);

for (int a = 1; a < 6; a++)
{
    xyvertices.Add(new List<float>());
    xyvertices[a].Add(a+1);
    xyvertices[a].Add(a+3);
}
xyvertices = xyvertices.Distinct().ToList();
Console.WriteLine("count:" + xyvertices.Count + "\n");

for (int i =0; i<xyvertices.Count; i++)
{
    Console.WriteLine(xyvertices[i][0]);
    Console.WriteLine(xyvertices[i][1]);
    Console.WriteLine();
}

Console.ReadLine();

The above code runs but nothing changes.

How can I make this work? Thanks

Bùi Đức Khánh
  • 3,975
  • 6
  • 27
  • 43
Cgameworld
  • 15
  • 1
  • 6
  • for non-standtart List(or arrays) in your case `List>`, you must implement [IEqualityComparer](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.iequalitycomparer-1?view=netframework-4.8) – styx Jul 14 '19 at 07:28
  • I'm looking for the output List to be 2D, in the same format as the input – Cgameworld Jul 14 '19 at 07:34
  • @Cgameworld help us help you - share the output you expect – Mureinik Jul 14 '19 at 08:12
  • @Mureinik the expected output is to have only one copy of (2,4) which was added twice. – iakobski Jul 14 '19 at 08:14
  • Though I agree with you the description "nothing changes" is not a good statement of the problem. – iakobski Jul 14 '19 at 08:23

2 Answers2

0

Distinct is comparing the Lists, and as the first two Lists are distinct, even though they contain the same two numbers, they are not Equal.

Your outer List is a list of x,y pairs so rather than code these as arbitrary Lists of floats, you can use a Tuple. For example:

List<(float, float)> xyvertices = new List<(float, float)>();
xyvertices.Add((2, 4));
for (int a = 1; a < 6; a++)
{
    xyvertices.Add((a+1,a+3));
}

xyvertices = xyvertices.Distinct().ToList();
Console.WriteLine("count:" + xyvertices.Count + "\n");
for (int i = 0; i < xyvertices.Count; i++)
{
    Console.WriteLine(xyvertices[i]);
    Console.WriteLine();
}
iakobski
  • 1,000
  • 7
  • 8
  • Incidentally, comparing `float`s for equality is not good practice as they are not a precise type, use `Decimal` or `int` as appropriate. – iakobski Jul 14 '19 at 08:21
0

You can use Linq GroupBy and gruop by first and second element as follows :

xyvertices = xyvertices.GroupBy(x=>new {first= x[0],second= x[1] })
            .Select(x=>new List<float> { x.Key.first, x.Key.second })
            .ToList();

Output :

count:5

2
4

3
5

4
6

5
7

6
8
Mehrdad Dowlatabadi
  • 1,335
  • 2
  • 9
  • 11