Reputation: 1382
I have a list of arrays with 2 strings in each array. I need to check if the first string in each array matches a given number. I am assuming that linq is the best way to do this. I found a helpful SO answer here: Find an item in List by LINQ? It states to find an item in a list do this:
string result = myList.Single(s => s == search);
From the comments, I think I want to use SingleOrDefault. But how do I make it search the first item of each array in the list? Here is my list of arrays:
List<string[]> shipsLater = new List<string[]> {};
string[] itemArr = { item.pid, future };
shipsLater.Add(itemArr);
Upvotes: 1
Views: 23467
Reputation: 633
Your initial array structure is problematic. Careful conversion to a dictionary suddenly makes the implementation simple.
List<string[]> shipsLater = new List<string[]>
{
new []{ "pid1", "abc" },
new []{ "pid1", "xyz" },
new []{ "pid2", "123" }
};
Dictionary<string, IEnumerable<string>> lookupByPid = shipsLater
.GroupBy(g => g[0])
.ToDictionary(k => k.Key, v => v.Select(i => i[1]));
// now your lookups are as simple as...
IEnumerable<string> matches = lookupByPid["pid1"];
Upvotes: 0
Reputation: 71
You can use Dictionary()
for best performance result; if you want to use string[]
use this:
string result = myList.Single(s => s[0] == search);
Upvotes: 1
Reputation: 223392
So you have a List of arrays like:
List<string[]> list = new List<string[]>();
Now each array consist of two elements, and you want to compare if first element is equal to your search parameter. You can do:
var query = list.Where(arr=> arr.First() == search);
This will give you all those element in the list which matches your condition.
From your comment:
basically just true or false, did i find it or not
If you are only looking to get back a boolean result indicating whether the condition has met or not use Enumerable.Any
like:
bool result = list.Any(arr=> arr.First() == search);
if your parameter is of type int
then call ToString
like:
bool result = list.Any(arr=> arr.First() == search.ToString());
Upvotes: 4