2016-03-02 43 views
3

嗨我正在從這個簡單的程序,只需要從用戶5號碼,只要數字大於10和小於100.我的目標是刪除重複的號碼,只顯示NOT DUPLICATE號碼。假設我輸入23,23,40,56,37,我只輸出40,56,37。請幫助我。提前致謝。這裏是我的代碼:如何從數組中刪除重複的號碼?

static void Main(string[] args) 
    { 
     int[] arr = new int[5]; 
     for (int i = 0; i < 5; i++) 
     { 
      Console.Write("\nPlease enter a number between 10 and 100: "); 
      int number = Convert.ToInt32(Console.ReadLine()); 
      if (number > 10 && number <= 100) 
      { 
       arr[i] = number; 
      } 
      else { 
       i--; 
      } 

     } 

     int[] arr2 = arr.Distinct().ToArray(); 
     Console.WriteLine("\n"); 
     for (int i = 0; i < arr2.Length; i++) 
     { 
      Console.WriteLine("you entered {0}", arr2[i]); 
     } 
     Console.ReadLine(); 
    } 
+0

p可以複製[this](http://stackoverflow.com/questions/9673/remove-duplicates-from-array) –

+0

@Ian我想他不想在列表中顯示重複的值..不同的將包括它一次 – Olivarsham

+0

@Olivarsham是的我不想顯示重複的值。正如你可以看到我已經使用Distinct(),但我不想顯示重複的值。任何想法如何解決這個問題? – zyxcom

回答

4

我認爲你正在尋找這樣的:

int[] arr2 = arr.GroupBy(x => x) 
       .Where(dup=>dup.Count()==1) 
       .Select(res=>res.Key) 
       .ToArray(); 

輸入數組: 23 , 23, 40, 56 , 37 輸出陣列:40 , 56 , 37

它是如何工作:

  • arr.GroupBy(x => x) =>給出{System.Linq.GroupedEnumerable<int,int,int>}一個集合,其中x.Key爲您提供了獨特的元素。
  • .Where(dup=>dup.Count()==1) =>解壓縮包含KeyValuePairs值計數正好等於1
  • .Select(res=>res.Key) =>從以上結果
2

在你的情況下,將需要也許是的LINQ方法的組合:

int[] arr2; 
int[] nodupe = arr2.GroupBy(x => x).Where(y => y.Count() < 2).Select(z => z.Key).ToArray(); 
5

的一種方法是組中的元素根據輸入數收集鍵和濾波器組,其計數爲1

int[] arr2 = arr.GroupBy(e=>e)     
       .Where(e=>e.Count() ==1) 
       .Select(e=>e.Key).ToArray(); 

Demo