Reputation: 18659
I have a string “EMP1$0,EMP2$1,EMP3 $1, Emp4$ 0, emp44$1”
; these are employee codes separated by coma (,
). Each employee code is appended with their statuses (i.e. 1 for active and 0 for inactive and separated with $ sign). Employee code will not contain spaces, but space can be possible between employee code and $. I need to check if an employee code say “EMP4” is present in this string. Which will be best approach?
Any help is highly appreciable.
Edit:
var strResult = from string str in hdnEmpCodes.Value.Split(',')
where str.Length > 0 && str.Substring(0, str.IndexOf("$")).Trim() == lnkEmpCode.Text.Trim()
select str.ToString();
But it is not giving the desired output.
Upvotes: 1
Views: 4878
Reputation: 117144
If you start with the following:
var text = "EMP1$0,EMP2$1,EMP3 $1, Emp4$ 0, emp44$1";
Then you can perform this query to extract the "EMP" codes:
var query =
from x in text.Split(',').Select(_ => _.Trim())
let y = x.Split('$').Select(_ => _.Trim())
where y.Any()
select y.First();
This would give the following result:
It would now be a simple matter of checking if any of the returned values match.
var found = query.Any(x => x.ToUpperInvariant() == "EMP4");
Does this do what you need?
Upvotes: 2
Reputation: 223322
Use string.Contains
if(str.Contains("EMP4"))
EDIT: based on your comment.
Since you said in your question that your values will be comma separated. You may try the following.
string str = "EMP10, EMP44, EMP5"; //your sample string.
string[] tempArray = str.Split(',');
if (tempArray.Contains("EMP4")) //This will result in Not Found
{
Console.WriteLine("Found");
}
if (str.Contains("EMP4")) //But a simple string.Contains will result in matching
//it to EMP44
{
Console.WriteLine("here");
}
Upvotes: 2
Reputation: 5472
You could use a regex
Regex r = new Regex("EMP4[^\\d]");
Match m = r.Match(yourString);
if (m.Success)
{
// your code
}
This searches any EMP4 string not followed by another digit
Upvotes: 0
Reputation: 5801
you can use the string.Contains method
bool employeeExistsInString = string.Contains(yourString);
However would have been nice if you would have at least googled it first.
Upvotes: 3