s => s == 'w' - Help me understand this line of code [duplicate] - c#

This question already has answers here:
Can you explain lambda expressions? [duplicate]
(6 answers)
What does the '=>' syntax in C# mean?
(7 answers)
Closed 4 years ago.
I am new to C# and coding in general and have a question on one exercise I'm doing. I am following the exercises on w3resource and I came across a challenge where I have to solve this:
"Write a C# program to check if a given string contains 'w' character between 1 and 3 times."
My solution was this:
var theString = Console.ReadLine();
var theArray = theString.ToCharArray();
int betweenOneAndThree = 0;
for (int i = 0; i < theArray.Length - 1; i++)
{
if (theArray[i] == 'w')
betweenOneAndThree++;
}
Console.WriteLine(betweenOneAndThree >= 1 && betweenOneAndThree <= 3);
Console.ReadLine();
This worked just fine, but I checked their solution and it goes like this:
Console.Write("Input a string (contains at least one 'w' char) : ");
string str = Console.ReadLine();
var count = str.Count(s => s == 'w');
Console.WriteLine("Test the string contains 'w' character between 1 and 3 times: ");
Console.WriteLine(count >= 1 && count <= 3);
Console.ReadLine();
I can't see 's' being declared as a char variable and I do not understand what it does here. Can anyone please explain to me what s => s == 'w' does?
Yes, I have tried googling this. But I can't seem to find an answer.
Thank you in advance :)

This is a lambda expression.
In this case it declares an anonymous delegate which is passed to Count, whose signature for this overload specifies a Func<T, bool> which is a typed representation of an anonymous function which takes a T (the type of the object in the collection) and returns bool. Count() here will execute this function against each object in the collection, and count how many times it returned true.

str.Count(s => s == 'w') is basically a shortened way to say this:
result = 0;
foreach (char s in str)
{
if (s == 'w')
{
result += 1;
}
}
return result;

s => s == 'w' is Predicate delegate with lambda expression,
str.Count(s => s == 'w') simply counts the occurences of the characters w

Related

Problem with default value with lambda in Where function c# [duplicate]

This question already has answers here:
C# compiler error: "not all code paths return a value"
(9 answers)
Closed 2 years ago.
I have a task to find even or odds numbers in a list using LINQ lambda.
I simply have this code to do it, but the compiler says "not all code paths return a value in lambda expression". So I think I need a default value, but how can I implement it? I tried a few things but still don't work. Please give advice. Thanks.
list = list.Where(x =>
{
if (command == "odd")
return x % 2 != 0;
else if (command == "even")
return x % 2 == 0;
});
If the command is "notEvenOrOdd" what should be the result? The example code does not cover this case, and it will therefore fail.
Using a "command" to determine what to do is usually not a great design. An alternative would be two extension methods:
public static IEnumerable<int> WhereEven(this IEnumerable<int> list) => list.Where(x => x % 2 != 0);
public static IEnumerable<int> WhereOdd(this IEnumerable<int> list) => list.Where(x => x % 2 == 0);
You can then check the command outside the lambda and run one of the methods above depending on the result.
I meant if the if-else statement dont match the conditions. I tried this and it works.
list = list.Where(x =>
{
if (command == "odd")
return x % 2 != 0;
else if (command == "even")
return x % 2 == 0;
return false;
}).ToList();

How to find the index of an element in an array inside a lambda expression in c# [duplicate]

This question already has an answer here:
Index in the Select projection
(1 answer)
Closed 3 years ago.
I want to create a function that flips a string's order
example: "hi" => "ih"
here is the code I have come out with so far:
public static string Flip(this string Str)
{
char[] chararray = Str.ToCharArray();
string output = "";
chararray. //i dont know what methoud should be used to execute action
return output;
}
the thing is, i want to know within the lambda expression what is the index of the object that is currently selected ex:x in (x => x ) indexOf is not an option as there can be more then one char from the same type
how can I know the index?
edit:
I don't want to know how to reverse a string, I want to know how to find an index of an object in lambda expression
In the Select and Where extension methods of LINQ, you have an overload that takes two parameters in the lambda, the first is the element, the second is the index.
so in your case if you have a char array:
var reversedArray = charArray
.Select((c, i) => new { Element = c, Index = i })
.OrderByDescending(arg => arg.Index)
.Select(arg => arg.Element)
.ToArray();
This is just to demonstrate how to get the index in LINQ extesions methods.
As the question states this is not about how to reverse a string.

what is the alternative for Like operator in C#? [duplicate]

This question already has answers here:
C# snippet needed to replicate VBA Like operator
(3 answers)
Closed 8 years ago.
Q: I want to match string with pattern that has wild cards(* and ?). I know in VB.Net, I can do this with Like Operator but how do I do in C#?
Example in VB:
Private Sub Match()
Dim testCheck As Boolean
testCheck = "apple" Like "*p?e"
End Sub
Q: Code in C#?
In C#, you can use regular expressions:
bool matches = Regex.IsMatch("apple", ".*p.e");
Replacing:
* with .* (multiple characters, zero or more)
? with . (one character)
There is no operator like that in c#.
VB.NET compiles your code to following LikeOperator.LikeString method call:
bool testCheck = LikeOperator.LikeString("apple", "*p?e", CompareMethod.Binary);
You can call this method directly if you add reference to Microsoft.VisualBasic.dll and add using Microsoft.VisualBasic.CompilerServices, but I would not advise doing that.
You should probably learn regular expressions and use proper regex instead of Like operator. Expression equivalent to yours would be:
.*p.e
As others have pointed out, this is probably a job for regular expressions.
Nonetheless, I thought it might be fun to write a tiny extension method that implements this logic and came up with the following:
static class StringCompareExtensions
{
public static bool IsLike(this string s, string s2)
{
int matched = 0;
for (int i = 0; i < s2.Length; i++)
{
if (matched >= s.Length)
return false;
char c = s2[i];
if (c == '?')
matched++;
else if (c == '*')
{
if ((i + 1) < s2.Length)
{
char next = s2[i + 1];
int j = s.IndexOf(next, matched + 1);
if (j < 0)
return false;
matched = j;
}
else break; // '*' matches rest of s
}
else
{
if (c != s[matched])
return false;
matched++;
}
}
return (matched == s.Length);
}
}
You would use it like this:
string s = "12345";
Console.WriteLine(s.IsLike("1*5")); // Returns true
Of course, you could write the same method using regular expressions, which would be shorter and simpler than the one above.
EDIT:
I had a little time to play with this today. I ended up writing an article that presents several ways you can get the functionality of the Like operator from C#. The article is Implementing VB's Like Operator in C#.
There is no Like in C#. Use regular expressions to get the functionality you want.
You might want to start with this intro tutorial: C# Regex.Match
Regex.IsMatch("apple", "*p?e")
for simple pattern matching:
string.Contains()

How to check if a String contains any letter from a to z? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# Regex: Checking for “a-z” and “A-Z”
I could just use the code below:
String hello = "Hello1";
Char[] convertedString = String.ToCharArray();
int errorCounter = 0;
for (int i = 0; i < CreateAccountPage_PasswordBox_Password.Password.Length; i++) {
if (convertedString[i].Equals('a') || convertedString[i].Equals('A') .....
|| convertedString[i].Equals('z') || convertedString[i].Equals('Z')) {
errorCounter++;
}
}
if(errorCounter > 0) {
//do something
}
but I suppose it takes too much line for just a simple purpose, I believe there is a way which is much more simple, the way which I have not yet mastered.
What about:
//true if it doesn't contain letters
bool result = hello.Any(x => !char.IsLetter(x));
Replace your for loop by this :
errorCounter = Regex.Matches(yourstring,#"[a-zA-Z]").Count;
Remember to use Regex class, you have to using System.Text.RegularExpressions; in your import
You could use RegEx:
Regex.IsMatch(hello, #"^[a-zA-Z]+$");
If you don't like that, you can use LINQ:
hello.All(Char.IsLetter);
Or, you can loop through the characters, and use isAlpha:
Char.IsLetter(character);
You can look for regular expression
Regex.IsMatch(str, #"^[a-zA-Z]+$");
For a minimal change:
for(int i=0; i<str.Length; i++ )
if(str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
errorCount++;
You could use regular expressions, at least if speed is not an issue and you do not really need the actual exact count.
Use regular expression
no need to convert it to char array
if(Regex.IsMatch("yourString",".*?[a-zA-Z].*?"))
{
errorCounter++;
}

Left function in c# [duplicate]

This question already has answers here:
.NET equivalent of the old vb left(string, length) function
(11 answers)
Closed 3 years ago.
what is the alternative for Left function in c#
i have this in
Left(fac.GetCachedValue("Auto Print Clinical Warnings").ToLower + " ", 1) == "y");
It sounds like you're asking about a function
string Left(string s, int left)
that will return the leftmost left characters of the string s. In that case you can just use String.Substring. You can write this as an extension method:
public static class StringExtensions
{
public static string Left(this string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
maxLength = Math.Abs(maxLength);
return ( value.Length <= maxLength
? value
: value.Substring(0, maxLength)
);
}
}
and use it like so:
string left = s.Left(number);
For your specific example:
string s = fac.GetCachedValue("Auto Print Clinical Warnings").ToLower() + " ";
string left = s.Substring(0, 1);
It's the Substring method of String, with the first argument set to 0.
myString.Substring(0,1);
[The following was added by Almo; see Justin J Stark's comment. —Peter O.]
Warning:
If the string's length is less than the number of characters you're taking, you'll get an ArgumentOutOfRangeException.
Just write what you really wanted to know:
fac.GetCachedValue("Auto Print Clinical Warnings").ToLower().StartsWith("y")
It's much simpler than anything with substring.
use substring function:
yourString.Substring(0, length);
var value = fac.GetCachedValue("Auto Print Clinical Warnings")
// 0 = Start at the first character
// 1 = The length of the string to grab
if (value.ToLower().SubString(0, 1) == "y")
{
// Do your stuff.
}

Categories

Resources