如何从对象中的键和值匹配的 IGrouping 获取值

How to get value from IGrouping where key and value in object match

我有一个包含三列的数据库 table:代码类型、代码、名称

我将这些值保存在内存中,如果您愿意的话,这是一个穷人的缓存。

public class ShortCodeCache
{
    public DateTime LastRefresh { get; set; }

    public Lookup<string, ShortCode> CodeList { get; set; }
}

public class ShortCode
{
    public string CodeType { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

我从数据库中提取值并将它们分配给查找。

private static void GetShortCodeCache(DateTime current)
{
    try
    {
        using (SqlConnection cn = new MSSqlServerConnection().GetConnection())
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = Query;
                cmd.Connection = cn;
                cn.Open();

                List<ShortCode> codesList = new List<ShortCode>();

                SqlDataReader readline = cmd.ExecuteReader();
                while (readline.Read())
                {
                    ShortCode shortCode = new ShortCode
                    {
                        CodeType = readline["CodeType"].ToString().Trim(),
                        Code = readline["Code"].ToString().Trim(),
                        Name = readline["Name"].ToString().Trim()
                    };

                    codesList.Add(shortCode);
                }

                currentCache.CodeList = (Lookup<string, ShortCode>)codesList.ToLookup(code => code.CodeType);

                if (currentCache.CodeList.Count != 0)
                    currentCache.LastRefresh = current;

                if (log.IsDebugEnabled)
                {
                    log.Debug("LastCacheRefresh: " + currentCache.LastRefresh);
                }
            }
        }
    }
    catch (SqlException sqlex)
    {
        log.Error(sqlex.Message);
        throw;
    }
    catch (Exception ex)
    {
        log.Error(ex.Message);
        throw;
    }
        
    return; 
}

我相信到这里为止的这一部分是有效的。

我的问题是我无法获取特定代码类型和代码的名称。例如,我传入“DamageQuadrant”和“P9”,我需要名称值。

这是我目前拥有的,但 VS 对我咆哮说没有 CodeType 的定义。

public static string GetNameFromCode(string type, string code)
{
    CheckCodeCache();

    var codeType = currentCache.CodeList.Where(x => x.Key == type);
    string data = codeType.Where(x => x.CodeType, code).Name;

    return data;
}

我尝试了各种其他方法,包括在 Linq 代码中使用 && 条件。这看起来很容易,但到目前为止还不是。

首先:您忘记将 new ShortCodes 添加到 codesList,因此当前代码不会在您的查找中为您提供任何信息。

其次:使用ILookup<>而不是Lookup<>。您没有充分的理由指定实现类型。如果您只希望每个组合有一个可能的项目,请改用 IDictionary<>

第三:不要在查找或字典中使用 .Where()。请改用 [key] 语法。

第四步:在查找或字典中键入要查找的值。

public IDictionary<(string Type, string Code), ShortCode> ShortCodesByTypeAndCode { get; set; }
currentCache.ShortCodesByTypeAndCode = codesList.ToDictionary(code => (code.CodeType, code.Code));
return currentCache.ShortCodesByTypeAndCode[(type, code)].Name;