I need to extract first numeric value set from a string. Here (Link Here), I have found a RegEx way to do that. But, in my case I have a LINQ query from where I need to do the same logic.
Here is my exisiting Logic
bool Isbn = db.BibContents.Any(ad => ad.NormValue == ISBN); // I need to do the numeric split logic into the db column NormValue
Note
I cannot loop here to get values first and compare in the loop. Because, I have huge number of records in DB and NormValue Column is nvarchar(max) typed.
Any help to this will be appreciated.
Thanks
How about you parse your result to string? I don't know that much about LINQ but I would parse the result into String and use regex.
bool Isbn = db.BibContents.Any(ad => GetDigits(ad.NormValue) == ISBN);
public string GetDigits(string text) {
return string.Join("",text.AsEnumerable().Where(char.IsDigit));
}
How about that?
Related
I have a date range come like this,
string ActualReleaseDates ="7/8/2016, 7/9/2016, 7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
string NewsReleasedDate ="07/11/2016";
I want to check NewsReleaseDate is inside the ActualReleaseDates
But in the following code it return as a false.
if (ActualReleaseDates.Split(',').Contains(NewsReleasedDate.TrimStart(new Char[] { '0' })))
{
//some code here
}
The immediate problem is that after splitting your ActualReleaseDates string, there isn't an entry of "7/11/2016"... instead, there's an entry of " 7/11/2016"... note the space.
But more fundamentally, just trimming the start of NewsReleasedDate won't help if the value is something like "07/08/2016"... what you should be doing is handling these values as dates, rather than as strings:
Split ActualReleaseDates by comma, then parse each value (after trimming whitespace) in an appropriate format (which I suspect is M/d/yyyy) so that you get a List<DateTime>.
Parse NewsReleasedDate in the appropriate format, which I suspect is MM/dd/yyyy, so you get a DateTime.
See whether the parsed value from the second step occurs in the list from the first step.
(I'd personally recommend using Noda Time and parsing to LocalDate values, but I'm biased...)
Fundamentally, you're trying to see whether one date occurs in a list of dates... so make sure you get your data into its most appropriate representation as early as possible. Ideally, avoid using strings for this at all... we don't know where your data has come from, but if it started off in another representation and was converted into text, see if you can avoid that conversion.
The white space problem. You can use trim() and ' 7/11/2016' will be '7/11/2016'
var ActualReleaseDates = "7/8/2016, 7/9/2016, 7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
var NewsReleasedDate = "07/11/2016";
var splitActualReleaseDates = ActualReleaseDates.Split(',').Select(x => x.Trim());
if (splitActualReleaseDates.Contains(NewsReleasedDate.TrimStart(new Char[] { '0' })))
{
}
You can use linq to convert your strings into DateTime objects and compare them instead of strings
string ActualReleaseDates ="7/8/2016,7/9/2016,7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
string NewsReleasedDate ="07/11/2016";
var releaseDates = ActualReleaseDates.Split(',').Select(x => DateTime.Parse(x));
var newsReleased = DateTime.Parse(NewsReleaseDate);
if (releaseDates.Contains(newsReleased))
{
//some code here
}
please note that DateTime is parsed respectively to the current Culture. You can use DateTime.ParseExact if you want to specify exact date format.
You can Prase to DateTime before doing the query like this:
(I think this is the most accurate and guaranteed way to compare dates)
Func<string, DateTime> stringToDate = s => DateTime.ParseExact(s.Trim(), "M/d/yyyy",
CultureInfo.InvariantCulture);
DateTime newReleaseDateTime = stringToDate(NewsReleasedDate);
bool result = ActualReleaseDates.Split(',').Select(x => stringToDate(x))
.Contains(newReleaseDateTime);
It returns false because of the date 07/11/2016 stored in NewsReleasedDate is stored as string with a '0' at the begining. And in the ActualReleaseDates string you have white spaces between the ',' and numbers.
Try to rewrite theese strings like this :
ActualReleaseDates ="7/8/2016,7/9/2016,7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016"; // white spaces removed.
and the variable like this :
NewsReleasedDate ="7/11/2016"; // 0 removed
This is my code example :
string ActualReleaseDates = "7/8/2016,7/9/2016,7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
string NewsReleasedDate = "7/11/2016";
string[] dates = ActualReleaseDates.Split(',');
Console.WriteLine(dates.Contains(NewsReleasedDate));
This is not the best way to compare dates, you can use Date class which is usefull to do this kind of comparations.
I've loaded a table from excel in C# using the ExcelDataReader package, however I'm struggling to write a method which returns the value of a cell as a string, based on the row number and column name.
I have a solution for a method that works if there are just strings in the DataTable...
public string ReadData(int rowNum, string columnName)
{
DataRow row = table.Rows[rowNum];
string value = row.Field<string>(columnName);
return value;
}
(the DataTable variable 'table' is loaded elsewhere)
..however I would like also like to be able to return numbers and dates (as strings).
I feel I might need to edit this part somehow...
string value = row.Field<string>(columnName);
But I don't know how to make it so it pulls back whatever value and type is in that field and returns a string.
Many thanks!
You can simply use the by-name-indexer and call ToString():
string value = row[columnName].ToString();
You probably should check for null values:
string value = (row[columnName] ?? string.Empty).ToString();
You could use, DataRow name-indexer returns an object on which we can call .ToString() to convert it to string.
return row[columnname].ToString();
Use
string value = Convert.ToString(row[columnName]);
Using Convert.ToString() is preferrable because it does not only check for null but also for DBNull, which is the value of the column when accessing a real database where the column has no content.
In C# 6.0:
return row[columnName]?.ToString();
I have a string that I would like to format the same way I would a numeric value.
Ex:
int num = 2;
string option = num.ToString("000");
Console.WriteLine(option);
//output
//002
But the only way I can think to format it is to parse it as an int, then apply the ToString("000") method to it.
string option = "2";
option = int.Parse(option).ToString("000");
Is there a better, more direct way to do this?
No, there is no built-in mechanism to "format" a string as if it were a number. Some options:
Use string functions (Pad, Length, Substring) to determine what characters should be added
Parse to a numeric type and use ToString with numeric formatting strings
Use a reqular expression to extract the digits and generate a new string
There's not one "right" answer. Each has risks and benefits in terms of safety (what if the string does not represent a valid integer?), readability, performance, etc.
Would this suit your requirement?
string x = "2";
string formattedX = x.PadLeft(3, '0');
Console.WriteLine(formattedX); //prints 002
I m looking for a way to convert a string to a unique Id.
Ideas invited for an algorithm that comes up with a unique number for each string sent to it.
I tried to use hash code but then realized that two strings could have the same hash code.
How do I generate a unique code for each string as input and two same strings should generate me the same id at all times.
Can you have characters in your "unique ID"? If so, this should work ;-)
public string MakeUnique(string s)
{
return s;
}
All ID's will be unique to the value provided. The same string, will produce the exact same ID. That's what you wanted right?
If it's an integer result you want, how about converting each character to an int...
public int MakeUnique(string s)
{
string result = "";
foreach(var c in s)
{
result += ((int)c).ToString();
}
return Int.Parse(result);
}
WARNING: This will break if the string is too big
Simply append or prepend a guid:
string foo = "MyString";
//Simply throw it on the end
string uniqueString = foo + Guid.NewGuid();
//Prepend with underscore
string uniqueString = String.Format("{0}_{1}", foo, Guid.NewGuid());
//Append with underscore
string uniqueString = String.Format("{0}_{1}", Guid.NewGuid(), foo);
Edit (new requirement)
You have not provided enough information for me to post a great answer to this question. For example, environment (web, winforms, etc.) would be beneficial.
To point you in the right direction...
If the unique string that is returned needs to be the same when you pass in a string a second time, you could maintain a history of generated strings and check it each time generation is requested.
Truthfully, there are lots of ways to skin this cat...
If the original string is sensitive, similar to Gravatar, you could encrypt the string with MD5 encryption
As you have stated, and #Austin Salonen commented, they're not 100% unique, but the risk is low:
How are hash functions like MD5 unique?
A string can be fairly long and consists of charactes, which are 16-bit values. The number of possible strings is huge (much more than the range of integer or Guid). So you can't have a function that "just" translates a string into some guaranteed unique code, without some help.
You could use a database table: lookup your string in the table. If it's not there, insert it, generating a new (sequential) unique id. If it's there, use that id. The number of possible strings is huge, the number of strings you encounter, probably not.
I am adding a string (a) to another string (b) before I store it in DB, when I retrieve the value from DB, I want to remove the string(b) from string (a). string (b) is a constant. How can I do it
string a= "text1";
string b="text2";
string c = a+b;
I want to remove b from c after I retrive it from db
c = c.Replace(b, "");
Would be a simple way to do so.
Rather than do any of that, create a computed column in the DB that has the extra text.
Less storage; less code.
Try String.Replace - MSDN documentation here.
As #SvenS has pointed in #Khaled Nassar answer, using String.Replace won't work "as is" in your situation.
One acceptable solution may #Mitch's one, but if you don't have that access to modify your database, maybe there's another solution in pure C#:
int indexOfB = c.LastIndexOf(b);
string cWithoutB = c;
if(indexOfB >= 0)
{
c.Substring(0, indexOfB);
}
This prevents replacing more than once the same string as b, because who knows if some user save the same text as b and logic shouldn't be removing it if it's not the one predefined by your application.