编写修改ac#集合的方法时,有什么好的做法

Dav*_*rke 2 c# coding-style

我正在重构一些代码,我编写了一个修改Dictionary并返回它的方法.这比使用out参数更好吗?我真的不想在这种情况下创建一个扩展方法,因为它会将方法添加到Dictionary类中,这对于它的用途来说是过度的.请不要指出我不应该使用动态sql,这是目前必须推迟的重构中的另一个阶段.

private static Dictionary<int, string>
            FindMatches(Dictionary<int, string> records,
                        string queryFormat,
                        string region,
                        string type,
                        string label)
{
    var query = string.Format(queryFormat, SqlSvrName, SqlDbName, SqlSchemaName,
                                                             region, type, label);
    using (var dr = DataRepository.Provider.ExecuteReader(CommandType.Text, query))
    {
        if (dr != null && !dr.IsClosed)
        {
            while (dr.Read())
            {
                var assetID = (int)dr.GetDouble(0);
                if (!records.ContainsKey(assetID))
                    records[assetID] = dr.GetString(1);
            }
        }
    }
    return records;
}
Run Code Online (Sandbox Code Playgroud)

编辑:我是有点仓促与我一词的使用上面.我试图在我的代码中明确表示该方法修改了字典.这里的out参数只有在方法创建了一个新字典并通过该参数返回时才有意义.为此更多的上下文是使用不同的查询字符串多次调用该方法,并且字典可能已经包含匹配.

编辑2:只是为了跟进我删除了记录参数,而是从FindMatches返回KeyValuePair列表.我最终通过以下方式转换为字典:List<KeyValuePair<int, string>>

records
    .GroupBy(rec => rec.Key)
    .ToDictionary(grp => grp.Key, grp => grp.First().Value);
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 9

你的方法为什么要修改现有的字典呢?它似乎没有使用现有的键/值,所以让这个方法只返回一个新的Dictionary<string, int>:

private static Dictionary<int, string>
            FindMatches(string queryFormat,
                        string region,
                        string type,
                        string label)
{
    var records = new Dictionary<int, string>();
    var query = string.Format(queryFormat, SqlSvrName, SqlDbName,
                              SqlSchemaName, region, type, label);
    using (var dr = DataRepository.Provider.ExecuteReader(CommandType.Text,
                                                          query))
    {
        if (dr != null && !dr.IsClosed)
        {
            while (dr.Read())
            {
                var assetID = (int)dr.GetDouble(0);
                // If each assetID in the database will be distinct, you 
                // don't need the "if" here, because you know the dictionary
                // is empty to start with
                if (!records.ContainsKey(assetID))
                {
                    records[assetID] = dr.GetString(1);
                }
            }
        }
    }
    return records;
}
Run Code Online (Sandbox Code Playgroud)

然后,您还可以编写一个单独的方法以特定方式合并两个字典 - 或者返回一个新字典,这是合并两个现有字典的结果.将这两个问题分开.