user3373603 user3373603 - 1 month ago 9
C# Question

How to remove duplicate List in my List<List<int>> object?

I have

List<List<int>>
object

var lists = new List<List<int>>
{
new List<int> { 20 },
new List<int> { 10, 10 },
new List<int> { 5, 15 },
//next two lists should be considered as equals and
//one of this should be removed from main list
new List<int> { 2, 18 },
new List<int> { 18, 2 },
};


Now I want to remove duplicate from the
lists
. For example, result list should remove one (4th or 5th list), and contain only four lists.

Answer

All the arithmetics like 20, 10 + 10, 5 + 15, 2 + 18 and 18 + 2 will be computed at the compile time, so at the run time you can't distinguish 20's from one another.

However, you may change design from sums (18 + 2) into just tems (18, 2):

// please, notice commas instead of +'s 
var lists = new List<List<int>>() {
  new List<int> { 20 },
  new List<int> { 10, 10 },
  new List<int> {  5, 15 },
  new List<int> {  2, 18 },
  new List<int> { 18,  2 },
}; 

In this case case you can implement duplicates eliminations

// simplest, providing that list doesn't contain null's
for (int i = 0; i < lists.Count; ++i) {
  // since we want to compare sequecnes, we shall ensure the same order of their items
  var item = lists[i].OrderBy(x => x).ToArray();

  for (int j = lists.Count - 1; j > i; --j)
    if (item.SequenceEqual(lists[j].OrderBy(x => x)))
      lists.RemoveAt(j);
}

Test

var result = lists.Select(line => string.Join(" + ", line));
Console.Write(string.Join(Environment.NewLine, result));

The output is

20
10 + 10
5 + 15
2 + 18