我是c#的新手,我不完全了解列表是如何工作的。这是我的情景...
我有List<List<string>>
看起来像这样,{ {x, y, value} }
。
示例:{ {1, 10, Red}, {6, 34, Black}, {2, 19, Yellow} }
我需要知道的是如何做到这一点,
if(x == 6 && y == 34)
然后值=黑色(在此示例中)。
我在List<List<string>>
中有100个项目。如何搜索前两个字符串(x和y)的值然后检索第三个值(“value”)的整个事物?
答案 0 :(得分:2)
我是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
。
答案 1 :(得分:1)
List<List<string>> lsts = new List<List<string>>
{
new List<string>{"1", "10", "Red"},
new List<string>{"6", "34", "Black"},
new List<string>{"2", "19", "Yellow"}
};
var values = lsts.Where(l => l[0] == "6" && l[1] == "34").Select(l => l[2]); // "Black"
答案 2 :(得分:0)
这段代码闻起来很糟糕,但它会是这样的:
var outerList = new List<List<string>>()
{
new List<string>() { x="1", y="10", c=(string)Colors.Red },
new List<string>() { ... },
new List<string>() { ... },
....etc....
};
outerList.Select(inner => inner.Where(a => a.x == 6 && a.y == 34).Select(a => a.c));
答案 3 :(得分:0)
作为另一个(可能更灵活)选项,定义一个新类:
public class Item
{
public int x;
public int y;
public Color value;
}
现在您可以拥有项的列表并使用Linq。例如:
List<Item> mylist;
var s = mylist.FirstOrDefault(a => a.x==6 && a.y == 36).value;
答案 4 :(得分:0)
List<List<string>>
结构:
public static void TestLists()
{
List<List<string>> lists = new List<List<string>> { new List<string>{"1", "10", "Red"},new List<string>{"6", "34", "Black"},new List<string>{"2", "19", "Yellow"}};
foreach (var aList in lists)
{
var p = new ListParser(aList);
if (p.IsValid)
{
if (p.x == 6 && p.y == 34)
{
Console.WriteLine($"Found desired list: x={p.x}, y={p.y}, Value={p.value}");
}
else
{
Console.WriteLine($"Found another list: x={p.x}, y={p.y}, Value={p.value}");
}
}
}
Console.ReadLine();
}
使用assisting
类ListParser
:
public class ListParser
{
public int x;
public int y;
public string value;
public bool IsValid = false;
public ListParser(List<string> row)
{
if (row != null && row.Count >= 3 && int.TryParse(row[0], out x) && int.TryParse(row[1], out y))
{
IsValid = true;
value = row[2];
}
}
}
这是输出: