如何遍历KeyValuePair类型的列表 [英] How to iterate through list of type KeyValuePair
本文介绍了如何遍历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)
推荐答案
我想你可以使用通用词典在这里为自己省去了很多麻烦......如果:
1.你的意图不是要有一个可能有的列表KeyValuePairs具有相同的Key:要使用Dictionary,Keys必须是唯一的!
I think you can use a generic Dictionary here and save yourself a lot of trouble ... if:
1. it is not the case that your intent is to have a List where there could be KeyValuePairs that had the same Key: to use a Dictionary the Keys must be unique !
// 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)];
试试这个
Try this
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;
}
试试这个
Try This
public Point GetKeyFromValue(Point p,List<KeyValuePair<Point, Point>> lp)
{
return lp.Where(d => d.Value == p).Select(d => d.Key).FirstOrDefault();
}
这篇关于如何遍历KeyValuePair类型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文