Home > Enterprise >  How to get filtered item by value index in C# Dictionary?
How to get filtered item by value index in C# Dictionary?

Time:09-22

I am trying to write a method which should return the item value based on value index and condition.

For example, in the below, if I pass index value as 0, it should return keys and first value from integer array which is not having value 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] }
    };

Expected O/P:

if I pass index value 0, and condition as != 5 then O/P should be

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

CodePudding user response:

You could achieve this in two steps:

  1. Get those items that do not start with 5
var res = _dict.Where(a => a.Value[0] !=5);
  1. Then populate a new Dictionary with the remaining keys and the first entry in their integer array
foreach(KeyValuePair<string,int[]> keyValuePair in res)
{
    result.Add(keyValuePair.Key, keyValuePair.Value[0]);
}

Complete code would look something like

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)
{
    Dictionary<string, int> result = new Dictionary<string, int>();

    var res = _dict.Where(predicate);

    foreach(KeyValuePair<string,int[]> keyValuePair in res)
    {
        result.Add(keyValuePair.Key, keyValuePair.Value[valueIndex]);
    }


    return result;
}

GetResult(valueIndex: 0, predicate: a => a.Value[0] != 5) then gives the result you want

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

CodePudding user response:

single line using LINQ

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