Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
lets say I have array of strings:
string[] digits = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "specific"};


How can I select only words that contain i at position 2 (index 1).
So that output is only: five, six, eight and nine?

What I have tried:

string[] digits = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "specific"};

            var res = digits.Where(w => "i".All(l => w.Contains(l)))
//I know this is incorrect... just provided my try

return res;
Posted
Updated 1-Mar-22 6:25am

How would you do it without LINQ? With LINQ it is the same:
C#
var res = digits.Where(w => w[1]=='i')
 
Share this answer
 
Comments
LuckyChloe 1-Mar-22 12:05pm    
Thank you!.
Without LINQ I was thinking it was possible to do it using if statements
Luc Pattyn 1-Mar-22 12:08pm    
The Where() method IS just an if statement!
Where(someCondition) is equivalent to
foreach(item in IEnumerable) {
    if (!someCondition) continue;
    /// proceed with this item
}
LuckyChloe 1-Mar-22 12:09pm    
I did not know that. I realized that they were similar but no in that way. Thank you.
OriginalGriff 1-Mar-22 12:29pm    
Be aware that what Luc says is an oversimplification - Linq methods aren't really the same as an "explicit loop" - they use something called "deferred execution" where the code isn't executed at all until you actually need it - and that can cause some real confusion if you aren't careful.
An IEnumerable (which is what the Where call will return) is not the same as a List!
Luc Pattyn 1-Mar-22 12:48pm    
I don't like overcomplicating things.
If you read "/// proceed with this item" as "yield return item" you're pretty close to what is really going on, the foreach code is being generated by the compiler and the whole thing IS an IEnumerable.
But I'm afraid that is too much information for a first LINQ encounter.
You can also use Regex[^]. See:
string[] digits = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "specific"};

string pattern = @"^\w{1}i";
Regex r = new Regex(pattern);

var result = digits.Where(word => r.IsMatch(word)).ToList();


^\w{1}i pattern means:
^ - asserts position at start of a line
\w{1} - matches any word character (equivalent to [a-zA-Z0-9_]), exactly one occurence
i - find exact match, a letter i

More at: regex101: build, test, and debug regex[^]
 
Share this answer
 
Comments
LuckyChloe 1-Mar-22 13:52pm    
We have not covered Regex yet but once we do will take a look at it ❤️
trying to learn LINQ first.
Maciej Los 1-Mar-22 15:05pm    
As you can see, i use Linq query and inside it - a regex method :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900