Find all rows in a list containing x or y?

Can I do this without going through the whole list?

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

the list is populated with approximately 300 lines of text.

next I want to search the list and create a second list of all lines that begin with "abc" or contain "xyz".

I know what I can do for everyone, but is there a better / faster way?

+3
source share
7 answers

You can use LINQ. This is no different than using performance foreach- this is pretty much what it does behind the scenes - but you may prefer the syntax:

var query = responseLines.Where(s => s.StartsWith("abc") || s.Contains("xyz"))
                         .ToList();

( IEnumerable<string>, List<string>, ToList.)

+7
var newList = (from line in responseLines
              where line.StartsWith("abc") || line.Contains("xyz")
              select line).ToList();
+4

:

List<string> responseLines = new List<string>();
List<string> myLines = responseLines.Where(line => line.StartsWith("abc", StringComparison.InvariantCultureIgnoreCase) || line.Contains("xyz")).ToList();

StartsWith Contains - Contains , StartsWith . , , , , , foreach.

+4

LINQ:

List<string> list = responseLines.Where(x => x.StartsWith("abc") || x.Contains("xyz")).ToList();
+3

- , , List, , , .

, List - . , , LINQ File.ReadLines List<string>.

    var query = File.ReadLines("input.txt").
        Where(s => s.StartsWith("abc") || s.Contains("xyz"))
        .ToList();
+2

LINQ , (. LukeH ), , .

, - , "abc" "xyz", , , .

, , , " ".

+1

, , , . , , , - . , , , , "abc" "xyz."

, , , - , .

+1

Source: https://habr.com/ru/post/1772958/


All Articles