I'm trying to simplify and optimize the following lambda expression. My requirement is to get the first lead whose mobile phone or telephone1 matches intakePhoneNum. I want to match first 10 digits only.
Entity matchingLead =
allLeads.Where(l =>
(l.Attributes.Contains("mobilephone") &&
(Regex.Replace(l.Attributes["mobilephone"].ToString(), "[^0-9]", "").Length >=10
? Regex.Replace(l.Attributes["mobilephone"].ToString(), "[^0-9]", "").Substring(0,9)
: Regex.Replace(l.Attributes["mobilephone"].ToString(), "[^0-9]", "").Substring(0)).Equals(intakePhoneNum))||
(l.Attributes.Contains("address1_telephone1") &&
(Regex.Replace(l.Attributes["address1_telephone1"].ToString(), "[^0-9]", "").Length >= 10
? Regex.Replace(l.Attributes["address1_telephone1"].ToString(), "[^0-9]", "").Substring(0, 9)
: Regex.Replace(l.Attributes["address1_telephone1"].ToString(), "[^0-9]", "").Substring(0)).Equals(intakePhoneNum))).FirstOrDefault();
First, I would suggest to introduce variables for the attributes.
Then, instead of the differentiation between Length >= 10 and Length < 10, simple use StartsWith.
And last, instead of Where(...).FirstOrDefault, simply use FirstOrDefault(...)
Entity matchingLead =
allLeads.FirstOrDefault(l =>
{
if (l.Attributes.Contains("mobilephone"))
{
var phone = Regex.Replace(l.Attributes["mobilephone"].ToString(), "[^0-9]", "");
if (phone.StartsWith(intakePhoneNum))
return true;
}
if (l.Attributes.Contains("address1_telephone1"))
{
var phone = Regex.Replace(l.Attributes["address1_telephone1"].ToString(), "[^0-9]", "");
if (phone.StartsWith(intakePhoneNum))
return true;
}
return false;
});
does anybody have an idea why following code outputs 1000% for RebatePercent=10 :
return RebatePercent > 0 ? $"{RebatePercent.ToString("0%")}" : "-";
I didn't find anything to output 10%
thx
you can use as:
RebatePercent > 0 ? String.Format("{0}%", RebatePercent) : "-";
and in C#6:
RebatePercent > 0 ? $"{RebatePercent}%" : "-";
If you want to keep the use of string interpolation then you can just:
return RebatePercent > 0 ? $"{RebatePercent.ToString()}%" : "-";
I Have a string array with 5 values, i want the program to loop even though i don't enter a value for the arrays. If I split the arrays without inserting anything (pressing ..... (5 times "." to split the array) then it doesn't crash it will just loop. But if i just hit enter, then the program crashes.
Is there a way to fix the loop so that even though there is no kind of input, that it won't crash? (It also crashes if you don't complete all 5 values.)
Net = Console.ReadLine();
string[] oktet = new string[5];
oktet = Net.Split('.', '/');
temp = oktet[0]; //inputs value of array in temp
NaN = int.TryParse(temp, out Net0);
temp = oktet[1];
NaN = int.TryParse(temp, out Net1);
temp = oktet[2];
NaN = int.TryParse(temp, out Net2);
temp = oktet[3];
NaN = int.TryParse(temp, out Net3);
temp = oktet[4];
NaN = int.TryParse(temp, out subnet);
}
while (!NaN | Net0 > 255 | Net0 < 0 | Net1 > 255 | Net1 < 0 | Net2 > 255 | Net2 < 0 | Net3 > 255 | Net3 < 0 | subnet > 32 | subnet < 0);
I know it's pretty amateur, but hey, we're here to learn right? :)
Thanks in advanced!
You can try to do something like this:
string[] oktet = Net.Split('.', '/'); // size array according to input
if (oktet.Length != 5) continue; // reloop on bad input
Those two lines of code replace these:
string[] oktet = new string[5];
oktet = Net.Split('.', '/');
I would just use some command line option library if you could (unless this is homework where you need to learn how to validate input, parse, etc.). See NDesk.Options (http://www.ndesk.org/Options), available via Nuget as well. See the following for required options: How to enforce required command-line options with NDesk.Options?
var userInput = Console.ReadLine();
var userInputSplit = userInput.Split('.', '/');
var numbers = userInputSplit.Select(word =>
{
int result;
if (byte.TryParse(word, out result))
return (byte?)result;
return (byte?)null; });
});
var inputComplete = number.Where(number => number.HasValue).Count() == 4;
The problem is that your variable oktet isn't an array of 5, because you're assigning something else in it.
string[] oktet = new string[5]; // Assigns an array of 5
oktet = Net.Split('.', '/'); //assigns the result of the split to the variable
So, oktet is has the result of the split, and its length.
BTW, Classes start with a capital letter, and the variables should start with a small letter.
Coding standards will make the code more readable, and will help you tell the difference between items.
I have a double and I want to format it with the following rules:
If there are no decimal places show just the number (see 100 example below)
If there are any decimal places show 2 decimal places
So, as a few examples:
100 --> 100
99.958443534 --> 99.96
99.1 -> 99.10
You could check if its a whole number, the use the type of formatting based on that:
string res = string.Format(((number % 1) == 0) ? "{0:0}" : "{0:0.00}", number);
What about:
var a = 100;
var b = 99.95844354;
var aAnswer = a.ToString("0.##"); //aAnswer is "100"
var bAnswer = b.ToString("0.##"); //bAnswer is "99.96"
You can use:
decimal a = 99.949999999M;
Math.Round(a, 2); // Returns 99.95
I need to be able to compare some month names I have in an array.
It would be nice if there were some direct way like:
Month.toInt("January") > Month.toInt("May")
My Google searching seems to suggest the only way is to write your own method, but this seems like a common enough problem that I would think it would have been already implemented in .Net, anyone done this before?
DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month
Although, for your purposes, you'll probably be better off just creating a Dictionary<string, int> mapping the month's name to its value.
You could do something like this:
Convert.ToDate(month + " 01, 1900").Month
If you use the DateTime.ParseExact()-method that several people have suggested, you should carefully consider what you want to happen when the application runs in a non-English environment!
In Denmark, which of ParseExact("Januar", ...) and ParseExact("January", ...) should work and which should fail?
That will be the difference between CultureInfo.CurrentCulture and CultureInfo.InvariantCulture.
One simply solution would be create a Dictionary with names and values. Then using Contains() you can find the right value.
Dictionary<string, string> months = new Dictionary<string, string>()
{
{ "january", "01"},
{ "february", "02"},
{ "march", "03"},
{ "april", "04"},
{ "may", "05"},
{ "june", "06"},
{ "july", "07"},
{ "august", "08"},
{ "september", "09"},
{ "october", "10"},
{ "november", "11"},
{ "december", "12"},
};
foreach (var month in months)
{
if (StringThatContainsMonth.ToLower().Contains(month.Key))
{
string thisMonth = month.Value;
}
}
You can use the DateTime.Parse method to get a DateTime object and then check its Month property. Do something like this:
int month = DateTime.Parse("1." + monthName + " 2008").Month;
The trick is to build a valid date to create a DateTime object.
You can use an enum of months:
public enum Month
{
January,
February,
// (...)
December,
}
public Month ToInt(Month Input)
{
return (int)Enum.Parse(typeof(Month), Input, true));
}
I am not 100% certain on the syntax for enum.Parse(), though.
You don't have to create a DateTime instance to do this. It's as simple as this:
public static class Month
{
public static int ToInt(this string month)
{
return Array.IndexOf(
CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
month.ToLower(CultureInfo.CurrentCulture))
+ 1;
}
}
I'm running on the da-DK culture, so this unit test passes:
[Theory]
[InlineData("Januar", 1)]
[InlineData("Februar", 2)]
[InlineData("Marts", 3)]
[InlineData("April", 4)]
[InlineData("Maj", 5)]
[InlineData("Juni", 6)]
[InlineData("Juli", 7)]
[InlineData("August", 8)]
[InlineData("September", 9)]
[InlineData("Oktober", 10)]
[InlineData("November", 11)]
[InlineData("December", 12)]
public void Test(string monthName, int expected)
{
var actual = monthName.ToInt();
Assert.Equal(expected, actual);
}
I'll leave it as an exercise to the reader to create an overload where you can pass in an explicit CultureInfo.
Public Function returnMonthNumber(ByVal monthName As String) As Integer
Select Case monthName.ToLower
Case Is = "january"
Return 1
Case Is = "february"
Return 2
Case Is = "march"
Return 3
Case Is = "april"
Return 4
Case Is = "may"
Return 5
Case Is = "june"
Return 6
Case Is = "july"
Return 7
Case Is = "august"
Return 8
Case Is = "september"
Return 9
Case Is = "october"
Return 10
Case Is = "november"
Return 11
Case Is = "december"
Return 12
Case Else
Return 0
End Select
End Function
caution code is in Beta version.
And answering this seven years after the question was asked, it is possible to do this comparison using built-in methods:
Month.toInt("January") > Month.toInt("May")
becomes
Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
t => t.Equals("January", StringComparison.CurrentCultureIgnoreCase)) >
Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
t => t.Equals("May", StringComparison.CurrentCultureIgnoreCase))
Which can be refactored into an extension method for simplicity. The following is a LINQPad example (hence the Dump() method calls):
void Main()
{
("January".GetMonthIndex() > "May".GetMonthIndex()).Dump();
("January".GetMonthIndex() == "january".GetMonthIndex()).Dump();
("January".GetMonthIndex() < "May".GetMonthIndex()).Dump();
}
public static class Extension {
public static int GetMonthIndex(this string month) {
return Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
t => t.Equals(month, StringComparison.CurrentCultureIgnoreCase));
}
}
With output:
False
True
True
If you are using c# 3.0 (or above) you can use extenders
I translate it into C# code in Spanish version, regards:
public string ObtenerNumeroMes(string NombreMes){
string NumeroMes;
switch(NombreMes) {
case ("ENERO") :
NumeroMes = "01";
return NumeroMes;
case ("FEBRERO") :
NumeroMes = "02";
return NumeroMes;
case ("MARZO") :
NumeroMes = "03";
return NumeroMes;
case ("ABRIL") :
NumeroMes = "04";
return NumeroMes;
case ("MAYO") :
NumeroMes = "05";
return NumeroMes;
case ("JUNIO") :
NumeroMes = "06";
return NumeroMes;
case ("JULIO") :
NumeroMes = "07";
return NumeroMes;
case ("AGOSTO") :
NumeroMes = "08";
return NumeroMes;
case ("SEPTIEMBRE") :
NumeroMes = "09";
return NumeroMes;
case ("OCTUBRE") :
NumeroMes = "10";
return NumeroMes;
case ("NOVIEMBRE") :
NumeroMes = "11";
return NumeroMes;
case ("DICIEMBRE") :
NumeroMes = "12";
return NumeroMes;
default:
Console.WriteLine("Error");
return "ERROR";
}
}
What I did was to use SimpleDateFormat to create a format string, and parse the text to a date, and then retrieve the month from that. The code is below:
int year = 2012 \\or any other year
String monthName = "January" \\or any other month
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
int monthNumber = format.parse("01-" + monthName + "-" + year).getMonth();
This code helps you...
using System.Globalization;
....
string FullMonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.UtcNow.Month);
GetMonthName Method - it returns string...
If you want to get a month as an integer, then simply use -
DateTime dt= DateTime.UtcNow;
int month= dt.Month;
I hope, it helps you!!!
Thanks!!!
int selectedValue = 0;
switch (curentMonth)
{
case "January":
selectedValue = 1;
break;
case "February":
selectedValue = 2;
break;
}
if (selectedValue != 0)
{
/* var list= db.model_name.Where(x => x.column== selectedValue);
return list; */
}
return Ok(selectedValue);
This code is for awk, but easily adaptable to C/C++/C#
— in awk, all indices are "1-based" instead of "0-based" - the leading edge "=" of the reference string is simply pre-shifting the positions. remove that "=" for any 0-based languages`
function __(_) { # input - Eng. month names, any casing, min. 3 letters
# output - MM : [01-12], zero-padded
return \
((_=toupper(_)) ~ "^[OND]" ? "" : _<_) \
(index("=ANEBARPRAYUNULUGEPCTOVEC", substr(_ "",_+=_^=_<_,_))/_)
}
The reference string might look odd at first -
the 2nd + 3rd letters of month names constitute a unique set
So OP can input the english name of the months, full or abbreviated, and it'll return a zero-padded 2-digit month number. If you need it to be in integer form, then just scrub out the middle line that performs the padding.
You'll notice only 1 input variable declared and no other temp variables whatsoever - one of awk's major strengths is its extreme agility when it comes to dynamic typing of variables,
even for truly illogical operations like taking the "0th-power" of a string variable like
"Boston" ^ 0
This would seamlessly coerce that variable to a numeric data type, with a new value of 1.
This flexibility enables the recycling and re-using of the input temp variable(s) for any other purpose the moment the original input value(s) is/are no longer needed.