【问题标题】:How to get filtered item by value index in C# Dictionary?如何在 C# 字典中按值索引过滤项目?
【发布时间】:2021-11-16 00:47:56
【问题描述】:

我正在尝试编写一个根据值索引和条​​件返回项目值的方法。

例如,在下面,如果我将索引值传递为 0,它应该从不具有值 5 的整数数组中返回键和第一个值。

public static Dictionary<string, int[]> _dict = new Dictionary<string, int[]>()
    {
        {"A", [1,0,3] },
        {"B", [5,1,5] },
        {"C", [7,11,5] },
        {"D", [0,1,5]},
        {"E", [14,0,5] },
        {"F", [5,1,5] }
    };

预期 O/P:

如果我传递索引值 0,并且条件为 != 5 那么 O/P 应该是

    {
        {"A", 1 },
        {"C", 7 },
        {"D", 0 },
        {"E", 14}
    };

【问题讨论】:

  • 你的方法签名是什么?到目前为止,您尝试过什么?
  • 您能否向我们展示您的尝试以及什么不适合您?
  • 以上代码无法编译,无效。
  • 如果您有兴趣获得帮助,提供有效代码是一个好的开始。字典初始化的每一行都应该类似于{"A", new []{1,0,3} },。当你说“预期的O/P:”时,什么是O/P?

标签: c# arrays asp.net


【解决方案1】:

您可以分两步实现:

  1. 获取那些不以5开头的项目
var res = _dict.Where(a => a.Value[0] !=5);
  1. 然后用剩余的键和整数数组中的第一个条目填充一个新的字典
foreach(KeyValuePair<string,int[]> keyValuePair in res)
{
    result.Add(keyValuePair.Key, keyValuePair.Value[0]);
}

或使用 LINQ

result = res.ToDictionary(keyValue => keyValue.Key, keyValue => keyValue.Value[valueIndex]);

完整的代码看起来像

public static Dictionary<string, int[]> _dict = new Dictionary<string, int[]>()
{
    {"A", new int[] {1,0,3 } },
    {"B", new int[] {5,1,5} },
    {"C", new int[] {7,11,5} },
    {"D", new int[] {0,1,5}},
    {"E", new int[] {14,0,5} },
    {"F", new int[] {5,1,5} }
};

static Dictionary<string, int> GetResult(int valueIndex, Func<KeyValuePair<string, int[]>, bool> predicate) =>
            _dict.Where(predicate)
                 .ToDictionary(keyValue => keyValue.Key, keyValue => keyValue.Value[valueIndex]);

GetResult(valueIndex: 0, predicate: a =&gt; a.Value[0] != 5) 然后给出你想要的结果

{
    {"A", 1 },
    {"C", 7 },
    {"D", 0 },
    {"E", 14}
};

【讨论】:

  • 当数组中不存在索引时,会抛出错误IndexOutOfRangeException。最好先检查一下。
【解决方案2】:

一行代码使用LINQ

var result = _dict.Where(x => x.Value[0] != 5).ToDictionary(x => x.Key, y => y.Value[0]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-17
    • 2022-01-22
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 2020-10-12
    • 2011-08-18
    相关资源
    最近更新 更多