indexers, enumerators

  • Thread starter Thread starter Andrzej Kaczmarczyk
  • Start date Start date
A

Andrzej Kaczmarczyk

Hi, I am receiving this exception

Error 3 Cannot apply indexing with [] to an expression of type
'System.Collections.Generic.IEnumerable<VisualSystems.DbObjects.DbClasses.DbColumn>'
C:\Visual Studio\PROJECTS\VisualSystems.DbObjects.DbClasses\DbObjectTable.cs
51 30 VisualSystems.DbObjects.DbClasses

on this line:

string primaryKeyName = "ID";
DbColumn primaryKeyColumn = this.DbColumns[primaryKeyColumnName];

I am calling methods of this class:
public class DbColumns {
private Dictionary<DataColumn, DbColumn> dictionary;
public DbColumns() {
this.dictionary = new Dictionary<DataColumn, DbColumn>();
foreach (DataColumn column in this.table.Columns) {
this.dictionary.Add(column, new DbColumn(column)); }
}

public IEnumerator<DbColumn> GetEnumerator() {
foreach (KeyValuePair<DataColumn, DbColumn> keyValuePair in
this.dictionary) {
yield return keyValuePair.Value;
}
}

public DbColumn this[string columnName] {
get {
foreach (DataColumn column in this.dictionary.Keys) {
if (column.ColumnName == columnName) { return
this.dictionary[column]; }
}
return null;
}
}

}

I need both access methods - array style [] and iterator via
foreach(DbColumn db in DbColumns)

How to make this compile?

CUIN Kaczy
 
I solved it.
What I didn't shown was the way I used this class:

protected DbColumns dbColumns;
public IEnumerable<DbColumn> DbColumns {
get {
if (this.dbColumns == null) {
this.dbColumns = new DbColumns(this.Table);
}
foreach (DbColumn dbColumn in this.dbColumns) {
yield return dbColumn;
}
}
}

You cannot apply brackets to IEnumerable,
promoting the dbColumns to public was the way, I only need to refactor it to
change the names. And even better (just thought about it, there is no need
to build enumerator here, since the DbColumns already is enumerable)

so the way to go would be

protected DbColumns dbColumns;
public DbColumns DbColumns {
get {
if (this.dbColumns == null) this.dbColumns = new DbColumns(this.Table);
return this.dbColumns;
}
}

thanks,

and merry christmas

CUIN Kaczy
 
Back
Top