我是 C# 新手,我不完全了解列表的工作原理。
List<T> 在底层实现为数组。所以当你写这样的东西时:
var names = new List<string>() {"George", "Jerry", "Cramer", "Elaine" };
您刚刚创建了一个列表,其中包含四个 string 类型。如果你要这样做:
// it will return George because it is accessing item at index 0
var name = names[0];
如果你这样做:
var anotherList = new List<List<string>>();
anotherList.Add(names);
您正在创建一个列表,该列表在每个索引处都有另一个列表。所以如果你这样做:
// It will return a list because each index has a list in it.
var item = anotherList[0];
在你的情况下,你应该做的是创建一个类,这会让事情变得更容易:
public class XyValueClass // or a better name
{
// Change to string if it is not integer
public int X { get; set; }
// Change to string if it is not integer
public int Y { get; set; }
public string Color { get; set; }
}
那么你可以这样做:
var xyValues = new List<XyValueClass>();
xyValues.Add(new XyValueClass { X = 1, Y = 10, Color = "Red" });
那么当你在搜索的时候,你可以这样做:
// this will return Red
var color = xyValues.Single(item => item.X == 1 && Y == 10).Color;
如果您知道该项目在那里并且只有一个符合该条件的项目,请使用Single。如果您知道可能只有一项或可能没有,请使用SingleOrDefault。如果您认为有 0 个或多个符合该条件的项目,请使用 Where。