Split each line of two words in a list, compare if they match, and count using Linq

Is it possible to split each line (containing 2 words) in the list, and then compare if both words are the same and assume that the entries are using Linq? For instance:

Say I have a list containing

list[0] = "bla bla";
list[1] = "bla heh";
list[2] = "heh heh";

In this case, the output of the counter should be 2.

my attempt:

var count = lst.Count(c => c.Split(.......)....

can't get past this.

Any help would be greatly appreciated.

+4
source share
4 answers

You can use the sentence Selectand then Count:

 int count = myList.Select(s => s.Split(' '))
                   .Count(a => a[0] == a[1]);

or you can use Countonly as follows:

 int count = myList.Count(s => s.Substring(0, s.IndexOf(' ')) == 
                                 s.Substring(s.IndexOf(' ') + 1));
+2
source
list.Select(c => c.Split(' ')).Count(y => y.Length >= 2 && y[0] == y[1]);
+3
source

Span<T> (. ) nuget 'System.Memory' - :

        int count = input.Count(x => 
        {
           int index = x.IndexOf(' ');
           if (index < 1 || index == x.Length - 1) return false;
           var span = x.AsSpan();
           return span.Slice(start:0, length:index)           // no allocation
               .SequenceEqual(
                   span.Slice(start: index + 1));             // no allocation
        });
+1
source

Same as the others, but if you have 3 or more words, it will check them against eachother and only count arrays that have the same words everywhere.

var result = test.Select(x => x.Split(' ')).Count(x => x.All(y => x[0] == y));
+1
source

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


All Articles