views:

88

answers:

1

I have a string array:

string[] Animals = {"Cat", "Dog", "Fish"};

I then want to determine which element contains the sequence "is" and return that entire element; in this case "fish"

If I want to find "gh", it does not exist in the list, so it should return the first element, in this case "Cat"

I've tried this linq code, but i don't think I'm doing the lambda part right.

int index = Animals.Where(x => x.IndexOf("is") >= 0).First().IndexOf("is")
string result = index > 0 ? Animals[index] : Animals[0];

This code throws this error:

Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: value

I think I'm close, I just can't seem to get it.

This method obviously isn't fool proof, it should return the first instance of "is" which could be problematic. My potential list is fairly small and the index word is always unique.

+6  A: 

Try this:

string result = Animals.FirstOrDefault(x => x.Contains("is")) ?? Animals.First();

(This will fail if the array contains no elements; what do you want to do in this case? You could try FirstOrDefault for the fallback expression as well - this will return null if the sequence is empty.)

Given your requirements, the code you posted has 2 issues:

  1. It uses Enumerable.First, which will throw an exception on an empty sequence i.e. if no item exists that matches the original predicate.
  2. The index you are using in the the second statement is the index of the "is" substring in the result of the first query, not the index of the result in the original array. Consequently, it does not make sense to use that number to index the original array.
Ani
I would recommend a `.FirstOrDefault()` with no lambda instead `animals[0]` after the ??, in case `animals` is null.
jball
@jball: That will still throw an exception if animals is `null`. It will, however, return `null` if the array is empty.
Ani
I don't care. That case cannot happen. It's already checked for. And thanks. This works. I've been using a .ToString() method where the "is" is and that seems to be failing to work correctly. I think my original code may work but your code definitely does so I don't care.
Shawn
Got it to work. I just had to check that my object was null before calling ToString(). Thanks.
Shawn
Ani
@Ani, good point.
jball
@Ani: I should probably do that, but I'm not that concerned about it. The null that I had to check for was in another completely separate object that was used inside the Contains(). I thought I had a check for if(obj == null) after I checked if (list == null). Oh well, it works now, so hippee. Thanks.
Shawn