Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement generic IEnumerable or IDictionary to avoid CA1006?

Out of curiosity i would like to know how to best implement a class that could be used to avoid the CA1006 warning

CA1006 : Microsoft.Design : Consider a design where 'IReader.Query(String, String)' doesn't nest generic type 'IList(Of IDictionary(Of String, Object))'.

This is the method that returns the generic type

public virtual IList<IDictionary<string, object>> Query(
    string fullFileName, 
    string sheetName)
{
    using (var connection = new OdbcConnection(
        this.GetOdbcConnectionString(fullFileName)))
    {
        connection.Open();
        return connection
            .Query(string.Format(
                CultureInfo.InvariantCulture,
                SystemResources.ExcelReader_Query_select_top_128___from__0_,
                sheetName))
            .Cast<IDictionary<string, object>>()
            .ToList();
    }
}

Something like

SourceData<T, U> Query(string fullFileName, string sheetName)
SourceData Query(string fullFileName, string sheetName)

EDIT:

Following Marc's suggestions I encapsulated the nested generic in this class

public class QueryRow : List<KeyValuePair<string, object>>
{
    protected internal QueryRow(IEnumerable<KeyValuePair<string, object>> dictionary)
    {
        this.AddRange(dictionary.Select(kvp => kvp));
    }
}
like image 469
mrt181 Avatar asked Feb 02 '23 11:02

mrt181


1 Answers

Firstly, note that it is a design guideline, not a compiler error. One valid approach here would be: ignore it.

Another might be - encapsulate it; i.e. return a List<QueryRow>, where QueryRow is a shallow wrapper over an IDictionary<string,object> with an indexer, i.e.

public class QueryRow {
    private readonly IDictionary<string,object> values;
    internal QueryRow(IDictionary<string,object> values) {
        this.values = values;
    }
    public object this[string key] {
        get { return values[key]; }
        set { values[key] = value; }
    }
}

then, since this is being accessed via dapper, fill via:

var data = connection.Query(....)
        .Select(x => new QueryRow((IDictionary<string,object>)x).ToList()

Another option (that I'm not hugely fond of), might be: return DataTable.

goes off to wash his hands after typing DataTable... gah! twice now

like image 194
Marc Gravell Avatar answered Feb 06 '23 10:02

Marc Gravell