c# - 具有多个键和每个键的多个值的字典

标签 c# .net dictionary multikey

大家好,我有一个要求,我必须分配多个键,并且对于多个键,我必须分配多个值

我的要求如下。我有每个员工的 EmpIDPayYrPayID

假设我得到的数据如下:

EmpID  1000    1000  1000   1000
PayYr  2011    2011  2011   2012
PayID    1      2     3      1

我想要我的字典,这样字典的键值结果如下:

1000 - 2011 - 1,2,3
1000 - 2012 - 1

我尝试了一些事情如下

public struct Tuple<T1, T2>
{
    public readonly T1 Item1;
    public readonly T2 Item2;

    public Tuple(T1 item1, T2 item2)
    {
        Item1 = item1;
        Item2 = item2;
    }
}

示例代码

for (int empcnt = 0; empcnt < iEmpID.Length; empcnt++)
    {
        for (int yrcnt = 0; yrcnt < ipayYear.Length; yrcnt++)
        {

            List<int> lst1 = new List<int>();
            var key1 = new Tuple<int, int>(iEmpID[empcnt], ipayYear[yrcnt]);
            if (!dictAddValues.ContainsKey(key1))
            {
                dictAddValues.Add(key1, lst1);
                lst1.Add(lst[yrcnt]);
            }
        }

    }

但是我没有得到我需要的结果所以任何人都可以帮助我。

最佳答案

就个人而言,我可能会使用 Dictionary of Dictionaries,例如IDictionary<int, IDictionary<int, IList<int>>> .不是 我不完全确定您打算如何访问或促进这些数据; 对我的建议的效率产生很大影响。从好的方面来说,它可以让您相对轻松地访问数据,当且仅当您按照设置词典的顺序访问数据。
(转念一想,简单的类型声明本身是如此丑陋和毫无意义,你可能想跳过我上面所说的。)

如果您随机访问字段,可能是一个简单的非规范化 ICollection<Tuple<int, int, int>> (或等价物)将必须做到这一点,根据需要在应用程序的其他部分进行聚合。 LINQ 在这里可以提供很多帮助,尤其是它的聚合、分组和查找功能。

更新:希望这能澄清:

var outerDictionary = new Dictionary<int, Dictionary<int, List<int>>>();

/* fill initial values
 * assuming that you get your data row by row from an ADO.NET data source, EF, or something similar. */
foreach (var row in rows) {
    var employeeId = (int) row["EmpID"];
    var payYear = (int) row["PayYr"];
    var payId = (int) row["PayID"];


    Dictionary<int, int> innerDictionary;
    if (!outerDictionary.TryGet(employeeId, out innerDictionary)) {
        innerDictionary = new Dictionary<int, int>();
        outerDictionary.Add(employeeId, innerDictionary);
    }

    List<int> list;
    if (!innerDictionary.TryGet(payYear)) {
        list = new List<int>();
        innerDictionary.Add(payYear, list);
    }

    list.Add(payId);
}

/* now use it, e.g.: */
var data = outerDictionary[1000][2011]; // returns a list with { 1, 2, 3 }

尽管如此,还是有所保留;见评论。

关于c# - 具有多个键和每个键的多个值的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9328852/

相关文章:

python - 对某些(不是全部)字典值执行操作

c# - ASP.NET 身份用户存储 : Why return Task?

c# - 何时添加 gridview 中自动生成的列?

c# - 无法在 .NET 4 的 IIS 中看到 .NET 用户

c# - .NET Core 2.0 日志记录损坏了吗?

python - 从字典列表中的字典值中查找唯一字符串对的优雅方法

python - 如何索引字典列表?

c# - 如何在dockerfile中复制引用项目的.csproj

c# - 如何使用 FirstOrDefault 避免 Object reference not set to instance of object 错误?

c# - MVC 在 View 中显示文件夹中的文件