How to convert int array into a dictionary with key and value in C#

1 Answer

0 votes
using System;
using System.Linq;
 
class Program {
    static void Main(string[] args) {
        int[] arr = { 1, 2, 3, 4, 5, 6 };

        var result = from n in arr.ToDictionary(k => k, v => (v % 2) == 1 ? "Odd" : "Even")
                        select n;

        foreach (var dict in result)
            Console.WriteLine("{0} is {1}", dict.Key, dict.Value);
    }
}
 
 
 
/*
run:
 
1 is Odd
2 is Even
3 is Odd
4 is Even
5 is Odd
6 is Even
 
*/

 



answered Dec 28, 2022 by avibootz
...