C 如何遍歷各類資料集合

2021-06-03 01:58:37 字數 1739 閱讀 3397

c#中遍歷各類資料集合的方法,這裡自己做下總結:

1.列舉型別

//遍歷列舉型別sample的各個列舉名稱

foreach (string sp in enum.getnames(typeof(sample)))

//遍歷列舉型別sample的各個列舉值

foreach (string sp in enum.getvalues(typeof(sample)))

2.遍歷arraylist(queue、stack)

這裡以string為例,當然arraylist中的元素可以是任何資料型別,遍歷時須確認arraylist中的元素都是同一資料型別。

//遍歷元素為string型別的佇列

foreach (string text in arraylist)

此外遍歷queue佇列和stack堆疊的方式與arraylist基本相同, 都可以使用foreach來迴圈遍歷,只不過乙個是先進先出另乙個是先進後出罷了。

3.winform窗體中的控制項

//遍歷尋找主窗體中的控制項,並將符合條件的控制項從窗體上去除

foreach (control ctl in this.controls)

4.hashtable雜湊表

dictionaryentry類需要引用system.collections

//遍歷完整雜湊表中的鍵和值

foreach (dictionaryentry item in hashtable)

此外還可以單獨遍歷雜湊表中的鍵或值。

//只遍歷雜湊表中的鍵

foreach (string key in hashtable.keys)

//只遍歷雜湊表中的值

foreach (string value in hashtable.values)

5.遍歷dataset和datatable中的行和列

//遍歷dataset中的表

foreach (datatable dt in dataset.tables)

//遍歷dataset中預設第乙個表中的行

foreach (datarow dr in dataset.tables[0].rows)

//遍歷dataset中預設第乙個表中的列

foreach (datacolumn col in dataset.tables[0].columns)

datatable遍歷行和列的方法和dataset類似,只是將dataset.tables[0]換成具體某張表就可以了。

另外還可以對datatable表進行sql查詢,然後再對查詢結果進行遍歷。

//遍歷dataset中表select執行查詢條件後的結果

foreach (datarow dr in dataset.tables[0].select(" month>6 and month<12 "))

6.遍歷datagridview中的行

//遍歷datagridview中的行

foreach (datagridviewrow dr in datagridview1.rows)

7.遍歷listbox和combobox中的item

一般foreach遍歷只能遍歷到listbox和combobox裡item的名稱,完整遍歷需要在繫結item的時候新增的item資料是個二元屬性自定義類的物件,將物件中乙個屬性的名稱作為displaymember(item名),另乙個作為displayvalue(item值)。這樣在遍歷的時候就可以把listbox和combobox中的item的名稱和值全部獲取出來了。

C 遍歷各類資料集合的方法

遍歷列舉型別sample的各個列舉名稱 foreach string sp in enum.getnames typeof sample 遍歷列舉型別sample的各個列舉值 foreach string sp in enum.getvalues typeof sample 這裡以string為例,...

C 中遍歷各類資料集合的方法

c 中遍歷各類資料集合的方法總結 1.列舉型別 遍歷列舉型別sample的各個列舉名稱 foreach string spin enum.getnames typeof sample 遍歷列舉型別sample的各個列舉值 foreach string spin enum.getvalues type...

C 連線各類資料庫的方法集合

本文列出了c 連線access sql server oracle mysql db2和sybase六種不同資料庫的程式原始碼和需要注意的點。1.c 連線access 程式 using system.data using system.data.oledb string strconnection ...