Wes
Wes

Reputation: 13

LINQ search List<string[]>; if [0] matches then return [1]

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

Answers (1)

Jashaszun
Jashaszun

Reputation: 9270

Here's what I would use. I couldn't think of a one-liner because .FirstOrDefault on an IEnumerable<string> returns null if the collection is empty, rather than "". I just found a better way, using the null-coalescing operator (??), 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

Related Questions