【问题标题】:C# Dictionary LINQC# 字典 LINQ
【发布时间】:2011-12-08 19:24:16
【问题描述】:

我有一个类可以返回数据库表中的所有项目(代码如下)。我还有一个包含键值对的字典。在我从函数返回数据之前,我可以查看字典内部并返回与我的 linq 中的键关联的值吗?

public IEnumerable<Code> Return_All_Codes()
        {
           return _db.Codes.ToList(); 
           //can the above list look inside my dictionary below and return Administrative when it find the number 1 for my code type?  


        }


 public Dictionary<int, string> GetCodeTypes()
        {

            var dict = new Dictionary<int, string>();
            dict.Add(1, "Administrative");
            dict.Add(2, "Regular");

            return dict; 
        }

上面的列表能否在我的字典中查找并在找到我的代码类型的数字 1 时返回管理?我的 LINQ 中有一种 IF 语句?如果为 1,则为管理,否则为常规。

【问题讨论】:

    标签: linq list dictionary


    【解决方案1】:

    您可以通过以下方式进行映射:

    var dict = GetCodeTypes();
    return _db.Codes.AsEnumerable().Select(code => dict[code.cType]).ToList();
    

    但是,我建议将字典存储在您的类中,以防止每次都创建它,尤其是在多次调用时。

    【讨论】:

    • 表格代码大约有5个字段,其中一个是cType。 cType 是一个 int,我想改为显示 Dictionary 中的值。上面的代码可以让我这样做吗?
    • @MikeB55 上面的代码将返回一个 List 包含字典中的相关字符串(现在)。如果您想要其他信息,您只需要更改选择以包含它...
    • 我在使用上面的代码时遇到了错误。错误:“System.Collections.Generic.Dictionary.this[int]”的最佳重载方法匹配有一些无效参数
    • @MikeB55 cType 不能是 int .. 检查并确定?也许是uint
    • 我的 cType 的类型是 Int32。我也试过这段代码: return _db.Codes.AsEnumerable().Select(code => dict[Convert.ToInt32(code.cType)]).ToList();我将 code.cType 转换为 Int32,但仍然出现错误。错误:无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.IEnumerable
    猜你喜欢
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    相关资源
    最近更新 更多