有没有办法用LINQ更有效地做到这一点?我认为可能需要一个三元 - 如果要容纳空字符串,我主要寻找正确的LINQ语法来匹配[a]并返回[b](如果有的话)。我没有找到任何东西就进行了搜索,但那是因为我无法想到要搜索的内容......
public static string getValue(List<string[]> input, string searchCriteria)
{
if (input.Count < 1)
{
return "";
}
for (int temp = 0; temp < input.Count; temp++)
{
if(input[temp][0].Equals(searchCriteria))
{
return input[temp][1];
}
}
return "";
}
答案 0 :(得分:1)
这就是我要用的东西。 我无法想到一个单行,因为我刚刚找到了一种更好的方法,使用null-coalescing运算符(element_answer
上的.FirstOrDefault
如果集合为空,则返回IEnumerable<string>
,而不是null
。""
),这是一个单行:
??
然而,这似乎更适合public static string getValue(List<string[]> input, string searchCriteria)
{
return (from arr in input
where arr[0] == searchCriteria
select arr[1]).FirstOrDefault() ?? "";
}
,在这种情况下它只会是:
Dictionary<string, string>