如何将键交换为值和将值转换为字典中的键

时间:2018-08-24 12:10:56

标签: c# dictionary swap

我想交换字典中的键和值

我的字典看起来像这样

validateEmail(val))

现在我要在字典中打印值

public static void Main(string[] args)
{
Dictionary<int,int> dic = new Dictionary<int,int>{{1,10}, {2, 20}, {3, 30}};
}

我得到了这个显示

 foreach (KeyValuePair<int, int> kvp in dic)
{

    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
            Console.ReadKey();
}

我想在键和值之间交换值。交换结果后,答案应该是这样

Key = 1, Value = 10
Key = 2, Value = 20
Key = 3, Value = 30

我做了lambda表达式,但它改变了,但是我需要其他方法来做。.

2 个答案:

答案 0 :(得分:4)

假设值是唯一的,则可以使用:

var dic = new Dictionary<int,int>{{1,10}, {2, 20}, {3, 30}};

var dic2 = dic.ToDictionary(x => x.Value, x=> x.Key);

它实际上不会交换双方,您将获得一本新的字典。

答案 1 :(得分:0)

尝试一下,我想你理解代码

namespace Swap
{
public class Class1
{
    public SortedDictionary<string, string> names;

    public void BeforeSwaping()
    {
        Console.WriteLine("Before Swapping: ");
        Console.WriteLine();
        names = new SortedDictionary<string, string>();
        names.Add("Sonoo", "srinath");
        names.Add("Perer", "mahesh");
        names.Add("James", "ramesh");
        names.Add("Ratan", "badri");
        names.Add("Irfan", "suresh");
        names.Add("sravan", "current");
        foreach (KeyValuePair<string, string> item in names)
        {

            Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);

        }
        Console.WriteLine();
    }

    public void AfterSwaping()
    {
        Console.WriteLine("After Swapping: ");
        Console.WriteLine();
        var key = names.Keys;
        var val = names.Values;

        string[] arrayKey = new string[key.Count];
        string[] arrayVal = new string[val.Count];
        int i = 0;
        foreach (string s in key)
        {
            arrayKey[i++] = s;
        }
        int j = 0;
        foreach (string s in val)
        {
            arrayVal[j++] = s;
        }
        names.Clear();
        //Console.WriteLine(arrayVal[0] + " " + arrayKey[0]);
        for (int k = 0; k < (arrayKey.Length + arrayVal.Length) / 2; k++)
        {
            names.Add(arrayVal[k], arrayKey[k]);
        }
        foreach (KeyValuePair<string, string> s in names)
        {
            Console.WriteLine("key:"+s.Key + ", "+"value:" + s.Value);
        }
    }
    public static void Main(string[] args)
    {
        Class1 c = new Class1();
        c.BeforeSwaping();
        c.AfterSwaping();
        Console.ReadKey();
    }
  }
}
相关问题