c# - 将列表中的不同项目添加到另一个列表

标签 c# list multidimensional-array unique

我想完成标题所述的任务,但我不知道如何去做。

我有 2 个列表:

public List<int[,]> LongList = new List<int[,]>();
public List<int[,]> UniqueList = new List<int[,]>();

为了进一步解释,这里有一个场景:

谜题:

public int[,] puzzle1 = new int [3,3] { {1,2,3},
                                            {8,4,0},
                                            {7,6,5} }; //[1,2,3;8,4,0;7,6,5]

    public int[,] puzzle2 = new int [3,3] { {8,7,6},
                                            {1,0,5},
                                            {2,3,4}  }; //[8,7,6;1,0,5;2,3,4]


    public int[,] puzzle3 = new int [3,3] { {7,6,3},
                                            {1,0,2},  
                                            {8,4,5}  }; //[7,6,3;1,0,2;8,4,5]

长列表包含:

LongList.Add(puzzle1); 
LongList.Add(puzzle1); 
LongList.Add(puzzle1); 
LongList.Add(puzzle1);
LongList.Add(puzzle2);
LongList.Add(puzzle2);
LongList.Add(puzzle3);
LongList.Add(puzzle3);
LongList.Add(puzzle3);

我想要唯一列表来保存 LongList 中的唯一值。 就好像这件事发生了:

UniqueList.Add(puzzle1);
UniqueList.Add(puzzle2);
UniqueList.Add(puzzle3);

作为一个等式:UniqueList = LongList 中的不同值

列表充满了多个重复出现的值,我只想取出唯一的值并将它们放入 UniqueList 中。

我正在尝试完成一个谜题,LongList 将包含同一谜题的多个引用以及更多内容。为了使讨论变得简单:

LongList 值:1,1,1,1,2,2,3,4,4,4,4,5,5

我希望 UniqueList 包含拼图:1,2,3,4,5

最佳答案

OP的评论含糊不清。

选项 1:所有多维数组中的唯一数字

List<int> UniqueList = new List<int>();

UniqueList = LongList.Select(i => Flatten(i))
               .SelectMany(i => i)
               .Distinct()
               .ToList();

这会将 { [[0, 1], [2, 3]], [[2, 2], [4, 5]] } 转换为 { 0, 1, 2, 3, 4, 5 }

参见下文 Flatten

选项 2:按值的唯一多维数组

注意:假设每个多维数组的大小和维数匹配。

List<int[,]> UniqueList = new List<int[,]>();
foreach (var e in LongList)
{
  IEnumerable<int> flat = Flatten(e);
  if (!UniqueList.Any(i => Flatten(i).SequenceEqual(flat)))
  {
    UniqueList.Add(e);
  }
}

这会将 { [[0, 1], [2, 3]], [[0, 1], [2, 3]], [[2, 2], [4, 5]] } 变为{ [[0, 1], [2, 3]], [[2, 2], [4, 5]] }

参见下文 Flatten

选项 3:仅唯一引用

UniqueList = aList.Distinct().ToList();

注意:这是原始答案,用于评论的背景。

展平方法

在所有情况下Flatten取自Guffa's SO Answer

public static IEnumerable<T> Flatten<T>(T[,] items) {
  for (int i = 0; i < items.GetLength(0); i++)
    for (int j = 0; j < items.GetLength(1); j++)
      yield return items[i, j];
}

其他选项

如果 OP 想要其他东西(例如,将 List<int[,]> 展平为 List<int[]> 或支持不同大小的多维数组),他们将不得不回复评论。

关于c# - 将列表中的不同项目添加到另一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15801478/

相关文章:

php - 如何去除多维数组中重复的键值数组

c# - 如果派生类继承基类的私有(private)成员,那么为什么不继承构造函数呢?

c# - lambda 表达式的扩展方法

类切片中的 Python 列表不起作用

list - 如何使用Hibernate PersistentBag不遵守List equals契约(Contract)?

java - 在 JAVA 中使用字符串作为多维数组的索引

c# - 在单个 If 语句中检查多个条件 - C#

c# - 该进程无法访问文件 '.mdf',因为该文件正在被另一个进程使用

python - NumPy 数组和 Python 列表有什么区别?

c - 二维数组的动态内存分配