Sach Sach - 1 year ago 80
C# Question

Using List<string>.Any() to find if a string contains an item as well as find the matching item?

I have a list of strings, which can be considered 'filters'.

For example:

List<string> filters = new List<string>();

I have another list of strings, which contains sentences.


List<string> msgList = new List<string>();
msgList.Add("This sentence contains the word Apple.");
msgList.Add("This doesn't contain any fruits.");
msgList.Add("This does. It's a banana.");

Now I want to find out which items in msgList contains a fruit. For which, I use the following code:

foreach(string msg in msgList)
// Do something.

I'm wondering, is there a way in Linq where I can use something similar to List.Any() where I can check if msgList contains a fruit, and if it does, also get the fruit which matched the inquiry. If I can get the matching index in 'filters' that should be fine. That is, for the first iteration of the loop it should return 0 (index of 'Apple'), for the second iteration return null or something like a negative value, for the third iteration it should return 2 (index of 'Banana').

I checked around in SO as well as Google but couldn't find exactly what I'm looking for.

Answer Source

You want FirstOrDefault instead of Any.

FirstOrDefault will return the first object that matches, if found, or the default value (usually null) if not found.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download