最佳答案
给出:
class Program
{
private static readonly List<(int a, int b, int c)> Map = new List<(int a, int b, int c)>()
{
(1, 1, 2),
(1, 2, 3),
(2, 2, 4)
};
static void Main(string[] args)
{
var result = Map.FirstOrDefault(w => w.a == 4 && w.b == 4);
if (result == null)
Console.WriteLine("Not found");
else
Console.WriteLine("Found");
}
}
在上面的示例中,在 if (result == null)
行遇到编译器错误。
CS0019运算符’= =’不能应用于类型为’(int a,int b,int c)’和’< null >’的操作数
在继续我的“发现”逻辑之前,我应该如何检查元组是否被发现?
在使用新的 c # 7元组之前,我需要这样做:
class Program
{
private static readonly List<Tuple<int, int, int>> Map = new List<Tuple<int, int, int>>()
{
new Tuple<int, int, int> (1, 1, 2),
new Tuple<int, int, int> (1, 2, 3),
new Tuple<int, int, int> (2, 2, 4)
};
static void Main(string[] args)
{
var result = Map.FirstOrDefault(w => w.Item1 == 4 && w.Item2 == 4);
if (result == null)
Console.WriteLine("Not found");
else
Console.WriteLine("Found");
}
}
效果不错。我喜欢新语法更容易理解的意图,但是不确定如何在执行发现(或不执行)之前检查它是否为 null。