skip to Main Content

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}
    };

2

Answers


  1. 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]);
    }
    

    or using LINQ

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

    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) =>
                _dict.Where(predicate)
                     .ToDictionary(keyValue => keyValue.Key, keyValue => keyValue.Value[valueIndex]);
    

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

    {
        {"A", 1 },
        {"C", 7 },
        {"D", 0 },
        {"E", 14}
    };
    
    Login or Signup to reply.
  2. One line code using LINQ

    var result = _dict.Where(x => x.Value[0] != 5).ToDictionary(x => x.Key, y => y.Value[0]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search