Reputation: 13
Is there a way to do this more efficiently with LINQ? I think there might need to be a ternary-if to accommodate the empty string, and I am mostly looking for the correct LINQ syntax to match [a] and return [b] (if there is one). I searched without finding anything, but that's on me because I couldn't really think of what to search for...
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 "";
}
Upvotes: 1
Views: 71
Reputation: 9270
Here's what I would use. I couldn't think of a one-liner because I just found a better way, using the null-coalescing operator (.FirstOrDefault
on an IEnumerable<string>
returns null
if the collection is empty, rather than ""
.??
), that is a one-liner:
public static string getValue(List<string[]> input, string searchCriteria)
{
return (from arr in input
where arr[0] == searchCriteria
select arr[1]).FirstOrDefault() ?? "";
}
However, this seems like it would be better suited for a Dictionary<string, string>
, in which case it would just be:
public static string getValue(Dictionary<string, string> input, string searchCriteria)
{
return input.ContainsKey(searchCriteria) ? input[searchCriteria] : "";
}
Upvotes: 1