本文介绍了如何遍历KeyValuePair类型的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有以下类型的列表

Hi I have following Type of list

private void PositionMatchList()
       {
           List<KeyValuePair<Point, Point>> lp = new List<KeyValuePair<Point, Point>>();
           KeyValuePair<Point, Point> p1 = new KeyValuePair<Point, Point>(new Point(0, 0), new Point(1, 1));
           KeyValuePair<Point, Point> p2 = new KeyValuePair<Point, Point>(new Point(0, 1), new Point(2,1));          
           lp.Add(p1);
           lp.Add(p2);          

       }



我希望在使用Linq传递密钥时获取值。例如,我想得到值(2,1)当键是(0,1)

推荐答案

// define the data structure outside your procedure so it can be accessed 
private Dictionary<Point, Point> dctPointPoint = new Dictionary<Point, Point>();

private void PositionMatchList()
{
    dctPointPoint.Add(new Point(0, 0), new Point(1, 1));
    dctPointPoint.Add(new Point(0, 1), new Point(2, 1));

    // this would throw an error: duplicate Key !
    // dctPointPoint.Add(new Point(0, 1), new Point(3, 1));
}

// use it in some method:

// initialize
PositionMatchList();

// access
Point pvalue = dctPointPoint[new Point(0, 1)];


class Point
    {
        public int X { get; set; }
        public int Y { get; set; }
        public Point(int a, int b)
        {
            X = a;
            Y = b;

        }
    }

    Point GetPoint(int key, int value)
    {
        List<KeyValuePair<Point, Point>> lp = new List<KeyValuePair<Point, Point>>();
        KeyValuePair<Point, Point> p1 = new KeyValuePair<Point, Point>(new Point(0, 0), new Point(1, 1));
        KeyValuePair<Point, Point> p2 = new KeyValuePair<Point, Point>(new Point(0, 1), new Point(2, 1));
        lp.Add(p1);
        lp.Add(p2);

        var temp = lp.Where(k => k.Key.X == key && k.Key.Y == value).FirstOrDefault();
        return temp.Value;

    }


public Point GetKeyFromValue(Point p,List<KeyValuePair<Point, Point>> lp)
{
      return lp.Where(d => d.Value == p).Select(d => d.Key).FirstOrDefault();
}


这篇关于如何遍历KeyValuePair类型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 04:47