2013-10-25 4 views
4

Скажем, у меня есть двумерный массив, который представляет простую матрицуУдалить повторяющиеся строки из двух dimentsional массива

int[,] matrix= new int[,] { { 1, 2 }, { 3, 4 }, { 1, 2 }, { 7, 8 } }; 

Похоже, что

1 2 
3 4 
1 2 
7 8 

Есть ли способ, чтобы удалить повторяющиеся строки с помощью LINQ и сделать массив таким?

1 2 
3 4 
7 8 
+0

Массивы статически размера. Вы не можете удалить элементы (но вы можете создать новый массив). – SJuan76

+0

Хороший вопрос. +1. –

ответ

3

Это на самом деле не Linq, но вы можете определить некоторые вспомогательный метод, как если бы они были методы Linq.

Чем проще алгоритм должен быть:

  1. Преобразование в список списка
  2. Нанести отчетливый с пользовательской компаратором
  3. Rebuild другой массив

Это выглядит следующим образом:

public static class MyExtensions 
{ 
    public static IEnumerable<List<T>> ToEnumerableOfEnumerable<T>(this T[,] array) 
    { 
     int rowCount = array.GetLength(0); 
     int columnCount = array.GetLength(1); 

     for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) 
     { 
      var row = new List<T>(); 
      for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) 
      { 
       row.Add(array[rowIndex, columnIndex]); 
      } 
      yield return row; 
     } 
    } 
    public static T[,] ToTwoDimensionalArray<T>(this List<List<T>> tuples) 
    { 
     var list = tuples.ToList(); 
     T[,] array = null; 
     for (int rowIndex = 0; rowIndex < list.Count; rowIndex++) 
     { 
      var row = list[rowIndex]; 
      if (array == null) 
      { 
       array = new T[list.Count, row.Count]; 
      } 
      for (int columnIndex = 0; columnIndex < row.Count; columnIndex++) 
      { 
       array[rowIndex, columnIndex] = row[columnIndex]; 
      } 
     } 
     return array; 
    } 
} 

Обычай Список Comparer (copied from a Jon Skeet's answer):

public class ListEqualityComparer<T> : IEqualityComparer<List<T>> 
{ 
    public bool Equals(List<T> x, List<T> y) 
    { 
     return x.SequenceEqual(y); 
    } 

    public int GetHashCode(List<T> obj) 
    { 
     int hash = 19; 
     foreach (var o in obj) 
     { 
      hash = hash * 31 + o.GetHashCode(); 
     } 
     return hash; 
    } 
} 

Использование:

[TestClass] 
public class UnitTest1 
{ 
    [TestMethod] 
    public void TestMethod1() 
    { 
     var array = new[,] { { 1, 2 }, { 3, 4 }, { 1, 2 }, { 7, 8 } }; 
     array = array.ToEnumerableOfEnumerable() 
        .Distinct(new ListEqualityComparer<int>()) 
        .ToList() 
        .ToTwoDimensionalArray(); 
    } 
} 
+0

+1 Если вы хотите использовать linq, вам нужен jagged массив, где его легче фильтровать. Поэтому требуется преобразование в Jagged – CarbineCoder

+0

Это просто работает как шарм! Большое спасибо за Вашу помощь. – Mitya

0
int[,] list = new int[,] { { 1, 2 }, { 3, 4 }, { 1, 2 }, { 7, 8 } };    
    List<KeyValuePair<Int32, Int32>> newList = new List<KeyValuePair<int,int>>(); 

    bool dupFound; 

     for (int i = 0; i < list.Length; i++) 
     { 
     dupFound = false; 

     for (int a = 0; a < list.Length; i++) 
      { 
      if ((i != a) && list[a, 0] == list[i, 0] && list[a, 1] == list[i, 1]) 
      { 
       dupFound = true; 
      break; 
        } 
      } 

       if (!dupFound) 
       { 
        var nonDup = new KeyValuePair<Int32, Int32>(list[i,0], list[i,1]); 
        newList.Add(nonDup); 
       } 
      } 
Смежные вопросы