Search code examples
c#.netstringliststartswith

How to find first or last string in list by StartsWith or Contains searching value without adding to another list


I'm trying to understand what variants I can use to get only one string with Contains or StartsWith first or last line, which contains searching value or starts with it. But without creating of new list and taking of first or last line from there, which result is actually answer to this question, but I wondering if it is possible to get it directly from the list, for example if list content is:

  List<string> list = new List<string>()
            {
                "data file collection k"
                "file name collection l",
                "file data collection m",
                "name data collection a",
                "name data collection b",
                "data name collection c",
                "data file collection d"
            };

and searching word:

string val = "name";

So this way:

foreach (string str in List) 
{ 
     if (str.StartsWith(val)) 
     { 
         // ...
     } 
}

result is:

name data collection a
name data collection b

or if look for whole string content for example:

  var mtchVal = list.Where(stringToCheck => stringToCheck.Contains(val)); 

result would be:

file name collection l
name data collection a
name data collection b
data name collection c

but desired result with StartsWith must be:

name data collection a

and by whole content:

file name collection l

Solution

  • If linq is allowed then

        var list = new List<string>();
        var first = list.FirstOrDefault(s => s.StartsWith("name"));
        var last = list.LastOrDefault(s => s.StartsWith("name"));