2012-04-23 206 views
0

對我的c sharp項目做一些用戶界面限制。 使用visual studio 2008和C#.net。C#在Datagridview中查找重複的值

所以我有一點代碼,它是一個嵌套的循環,應該通過列行運行並檢查是否有重複。

考慮一下我應該將文本更改爲可以打印出來的數組,因爲可以有多個副本。

簡而言之,有一個部分聯盟,增加一個是唯一的。用戶希望改變聯賽的部分,有些則會有所下降。

這是我到目前爲止。

public void CheckForDuplicate() 
    { 
     DataGridViewRowCollection coll = ParetoGrid.Rows; 
     DataGridViewRowCollection colls = ParetoGrid.Rows; 

     foreach (DataGridViewRow item in coll) 
     { 
      foreach (DataGridViewRow items in colls) 
      { 
       if (items.Cells[5].Value == item.Cells[5].Value) 
       { 
        if(items.Cells[2].Value != item.Cells[2].Value) 
        { 
         txtDupe.Text = items.Cells[2].Value.ToString(); 
         this.Refresh(); 
         dupi = false; 
        } 
       } 
      } 
     } 
    } 

什麼也沒有發生,一點都沒有,似乎總是錯誤的。一些奇怪的原因調試沒有捕捉任何東西。 所以我在流浪,如果有一個愚蠢的班輪我錯過了,或者如果有更好的方式來做到這一點?

非常感謝!

+0

Perhabs這將幫助你: http://stackoverflow.com/questions/9600950/how-to-count-duplicates-in-datagridview-in- c-sharp – HW90 2012-04-23 11:39:34

+0

奇怪的是,它確實有效,如果有重複,則將bool設置爲true。出於某種原因,儘管它不會在文本框中打印任何內容。任何原因? – lemunk 2012-04-23 14:04:14

回答

0

選擇獨特的LINQ應該這樣做。使用方法的語法,是這樣的:

public bool allUniqueRows() 
    { 
     var distinctCount = from r in ParetoGrid.Rows 
select r.whateverElement.Distinct().Count(); 
    if(distinctCount == ParetoGrid.Rows.Count()) 
    { 
    return true; 
    } 
    else 
    { 
    return false; 
    } 
    }