Rewrite Contains() method C# [closed] - c#

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I Have this clausule
if ((line.Contains('%')) || (line.Contains('#')) || (line.Contains("") && (!line.Contains(','))))
and i want rewrite it to one method,beacause this is too slow. Any ideas??

if(line.Intersect("%#,").Any())
or
if("%#,".Intersect(line).Any())
(Reversing the parameters may improve performance, depending on the type of data in line and the percentage of characters that match.)

Both the other answers seem to ignore the fact that the original code returns true when line contains % or # or when it does NOT contain ,. (the empty string being totally irrelevant).
The correct way to write this would be:
if(line.Intersect("%#").Any() || !line.Contains(","))
Or possibly:
char[] includes = { '%', '#' };
char[] excludes = { ',' };
if(line.Intersect(includes).Any() || !line.Intersect(excludes).Any())
Or this:
char[] includes = { '%', '#' };
char[] excludes = { ',' };
if(line.IndexOfAny(includes) != -1 || line.IndexOfAny(excludes) == -1)

First, lets simplify the whole statement. You use to many hooks:
if (line.Contains('%') || line.Contains('#') || line.Contains("") && !line.Contains(','))
Second, as stated before, line.Contains("") will always return true. Perhapse you are missing a space or something.
Last, searching a string (or an array of characters) for the orrucance of a character is FAST! The whole search-operation is just one simple operation at assembly level (REP SCASW). In this case you have to search for more than once characters, which will result in one or more simple assembly instructions. Other statements in C# are perhapse shorter, but probably not faster.
Search for a string inside a string is slightly slower, so try to remove the Contains("").
Other operations (with LINQ or REGEX) will probably result into more: memory-operations (for arrays, delegates, result types), more analyzation (multiple characters inside an array of characters), etc. etc.

Related

Confusing with LINQ and Lambda expressions in C# [duplicate]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
I need a discussion regarding the Performance of LINQ and Lambda Expression.
Which one is better?
I guess you mean query expression when talking about LINQ here.
They are equivalent. The compiler changes the query expression into the equivalent Lambda expression before compiling it, so the generated IL is exactly the same.
Example
var result = select s from intarray
where s < 5
select s + 1;
is exactly the same as
var result = intarray.Where( s => s < 5).Select( s => s+1);
Note that if you write the query expression like this:
var result = select s from intarray
where s < 5
select s;
It's converted to:
var result = intarray.Where( s => s < 5);
The final call to Select is omitted because it's redundant.
a quick comparison in reflector would probably do the trick. However, from a 'preference' standpoint, I find lambda statements easier to follow and write and use them across the board whether it be with objects, xml or whatever.
If performance is negligible, i'd go with the one that works best for you.
i actually started off a little topic looking at linq methods which may be of interest:
What's your favourite linq method or 'trick'
cheers..

Regex with leading zeros [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I need to match a filenames in the filelist with database rows by Regex.
File names are numbers with leading zeros
Database values are numbers without leading zeros
Sample file list:
0001.jpg
0002.bmp
...
0012.bmp
0013.bmp
0014.jpg
...
1012.jpg
...
1015.jpg
...
I use C#. And I need to match each file name with each row in the database.
You can use this regex
^0+\d+[.](jpg|bmp|jpeg|exe)
OR
^0+\d+[.]\S+
I'm somewhat reluctant to answer, but in order to match those file names (which is what I presume you are trying to do) you should try: \d{4}\.(jpg|bmp)
EDIT:
Since you are so liberal with your -1's..
Regex isn't really the correct technology to use to solve your coding problem, regex is used to find a string that matches a pattern.
The problem you appear to describe is that you have a poorly typed file system with unnecessarily added 0's and want to convert (for example) a 4 to 0004 and not care about what file extension you have.
The "best solution" to your problem is to fix the numbering system of your files or simply to add the leading 0's in c#, not to use a technology that is designed to do something completely different.
Enjoy your -6.

What do you call it when you pass a parameter to the next parameter [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I notice a lot of code where people do something like:
myClass.someMethod(something here, $1);
The $1 is picking up a value from "something here"?
What is this known as? I can't seem to find it anywhere? But this step, process is used in cases with regex quite a bit..
You'll often see this in regular expressions where $1 represents a capture group that you're carrying over into the new value.
For example, suppose we're building a tweet-parser for our website. We want to find # references in the tweet, and convert them into links to those particular accounts:
// Our Tweet
$t = "I am #jonathansampson, and I work with #appendTo.";
// Find every occurence of #something, capture 'something'
echo preg_replace("/#([a-z]+)/i", "<a href='http://twitter.com/$1'>$0</a>", $t);
Note here that we're matching every occurrence of #something, but we're wrapping the username portion in ( and ) so that we can handle it individually in our replacement text. The entire pattern is represented by $0, which will hold the value in its entirety from # to the last char in the username.
The same is true for JavaScript:
var tweet = "I am #jonathansampson, and I work with #appendTo.",
patrn = /#([a-z]+)/gi,
links = tweet.replace(patrn, "<a href='http://twitter.com/$1'>$&</a>");
The variable links now contains the value:
console.log(links);
/*
"I am <a href='http://twitter.com/jonathansampson'>#jonathansampson</a>, and
I work with <a href='http://twitter.com/appendTo'>#appendTo</a>."
*/
You might note that I used $& in JavaScript to grab the entire matched pattern while using $0 in PHP - we have to deal with these differences in life. My apologies ;)
If you are talking about javascript, $ can be used in declarations, so it could be a few things.
For example you could declare a variable as
var $1 = 1;
Then use it in your call
myClass.someMethod(something here, $1);
Equally it could be a reference to a function.

simple function to look if a integer in c# is a prime? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
is there a function or a simple class which let me check if a integer in c# is a prime or not?
No.
You'll need to write your own.
The basic algorithm for one single integer is to divide it by all integers up until it's square root and ensure that there is always a remainder.
To check more than one number, optimized algorithms such as the Sieve of Eratosthenes are available.
There is no reason to have a standard prime checking function.
This is an expensive computation which can be made in different ways, each one having different impacts on memory and cpu.
And it really depends on the size of the numbers and the sequence of number whose primality you'll have to test, as there are usually intermediate values to store.
Said otherwise : the solution you'll chose will have to be adapted to your program and your exact need. I suggest you start by looking at wikipedia (credit to Chris Shain for the link) and by existing libraries like this one for small integers (credits to Google for the link).
Here's the one I use for all my project euler problems.
private static bool IsPrime(long number) {
if (number <= 1) return false;
for (long i = 2; i <= Math.Sqrt(number); i++) {
if (number % i == 0)
return false;
}
return true;
}

How to use ?: operator [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
How would I convert the following code to use the ?: operator.. Is it Possible?
tbtotalamount.Text = string.Format("{0:n2}", dtl.Compute("sum(NetPay)", ""));
if (tbtotalamount.Text.Length == 0)
{
tbtotalamount.Text = "0";
}
The quoted code wouldn't benefit from using the ? : operator, which is called the conditional operator (sometimes called "the ternary operator" although technically, it's only a ternary operator — e.g., an operator that has three operands).
Typically the conditional operator is handy for when you have a variable and want to assign one of two values to it on the basis of a condition. So code in this form:
if (someCondition) {
a = "one value";
}
else {
a = "a different value";
}
can be rewritten
a = someCondition ? "one value" : "a different value";
In your case, though, you don't know that tbtotalamount.Text is blank until after you've done the string.Format, so you're better off leaving it with the if.
Yes. Here's how:
string test = string.Format("{0:n2}", dtl.Compute("sum(NetPay)", ""));
tbttotalamount.Text = test.length == 0 ? "0" : test;
Sorry to see so many downvotes, I'm not familiar with the ? (ternary) operator for a very long time either. I think it is very handy.
To the left of it is your test expression, it should be a boolean after evaluation. To the right is what the operator returns: if true, it will return the value to the left of the :. If false, the value to the right. Note that the whole expression returns something, and the compiler needs you to do something with it. You can't use the ternary operation to replace if-else statements that call functions whose return type is void.
What I mean to say is that a lot of people who've never used it before (like me) seem to think this is a pure if-else replacement, which it is not.

Categories

Resources