0

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);
Community
  • 1
  • 1
dmikester1
  • 1,374
  • 11
  • 55
  • 113

3 Answers3

3

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());
Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
  • There can only be one or none. Can I use SingleOrDefault instead of Where? – dmikester1 Mar 04 '15 at 18:17
  • @dmikester1, just to be clear, you mean there will be one item in the list which would match the condition ? if that is the case sure use `SingleOrDefault`, but it will return a `string[]` where first item would match your search criteria. – Habib Mar 04 '15 at 18:17
1

You can use Dictionary() for best performance result; if you want to use string[] use this:

string result = myList.Single(s => s[0] == search);
Alejo Ferrand
  • 71
  • 1
  • 3
0

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"];
Trevor Ash
  • 623
  • 4
  • 8