-3

Similar questions:
How to find substring in list of strings using LINQ
Find substring in a list of strings

Question:
I'm wondering if there's a method provided in C# .NET 4.5 which takes in a string and a delimiter as arguments and returns the element or index of element in a given List where the string is found delimited by the delimiter. Something like what Foo(string searchStr, char delimiter) does below?

Code:

        List<string> list = new List<string>();
        list.Add("XXX YYY ZZZ");
        list.Add("AAA BBB CCC");
        Console.WriteLine(list.Foo("XXX", ' '));    // should return 0 (index of element) or element of list
        Console.WriteLine(list.Foo("YYY", ' '));    // should return -1 or null
        Console.WriteLine(list.Foo("AAA", ' '));    // should return 1 (index of element) or element of list
        Console.WriteLine(list.Foo("DDD", ' '));    // should return -1 or null
Community
  • 1
  • 1
Petrus K.
  • 840
  • 7
  • 27
  • 56
  • IndexOf() should work. – Robert Harvey Jan 01 '15 at 17:24
  • @RobertHarvey It doesn't work as IndexOf matches the case and doesn't work for finding substrings in a given string. Also, I would have to specify that I want to delimit by a blank space ' ', no overloaded IndexOf method does that. – Petrus K. Jan 01 '15 at 17:28
  • Then you need to address your requirements more specifically in your question. The obvious answer is "write a function that does what you want." – Robert Harvey Jan 01 '15 at 17:30
  • My question is sufficiently specified (if you read the comments of the code where I have explained the desired output of the method). – Petrus K. Jan 01 '15 at 17:42

1 Answers1

0
Console.WriteLine(list.FirstOrDefault(x => x.StartsWith("XXX "));

This will return the element. If there is no element starting with "XXX ", it will return null, because that's the default for strings.

nvoigt
  • 75,013
  • 26
  • 93
  • 142