I have the following xmlnode (string) whose value would be of few given type i.e:
"Ansi_nulls","Encrypted","Quoted_identifer" etc.
I want to test the xmlnode using xmlNode.Contains ("xxx","yyy") ..
What is the correct syntax ?
If you are testing the full (complete) value of the node, you can do it by reversing the call; check that a list of known values contains your current node value:
new[]{"Ansi_nulls","Encrypted","Quoted_identifer", ...}.Contains(xmlNode);
I would create an extension method using sehes solution:
public static bool Contains(this string source, params string[] values)
{
return values.Any(value => source.Contains(value));
}
That way you can call:
xmlNode.Contains("string", "something else");
Contains takes a string to test for.
One way to solve your problem would be to use a simple regular expression
using System.Text.RegularExpressions;
if (Regex.IsMatch(nodevalue, "(Ansi_nulls|Encrypted|Quoted_identifer)")...
if (new[] {"xxx","yyy"}.Any(n => xmlNode.Contains(n)))
A simple if statement will work:
if (xmlNode.Contains("xxx") && xmlNode.Contains("yyy"))
{
// your work
}
Related
I'm using this code to check if the string (oCode/ originalCode) exists in the array (the string is written by user):
if (dic.cs.Any(code.Contains)) //dic.cs is in another class (cs is the array), the code variable is what I look for in the array
{
//I want to get the string was found in the array with the "Contains" function
}
I want to get the string that was found in the array with the Contains() function.
If it's possible to have multiple matches, then use this:
var foundCodes = dic.cs.Where(code.Contains);
foreach(var foundCode in foundCodes)
{
}
Otherwise:
var foundCode = dic.cs.FirstOrDefault(code.Contains);
if (!String.IsNullOrEmpty(foundCode))
{
}
You need a lambda expression in the Any method:
https://code.msdn.microsoft.com/LINQ-Quantifiers-f00e7e3e#AnySimple
var answer = yourArray.any(a => a == "WhatYouAreLookingFor");
if answer is true, then you found it.
I believe what you need is the array IndexOf method. https://msdn.microsoft.com/en-us/library/system.array.indexof(v=vs.110).aspx
I want to check if my array class has the string "Unavailable" contained for all elements:
classApplicantNDatesCount[] applicantCounts = null;
....
...
applicantCounts = appCount.ToArray();
Specifically this "part" of the array I need to search through:
applicantCounts[i].NadraDateAvailableforApplicant = "All Requested Slots UnAvailable"
So I need to check if all of applicantCounts[i].NadraDateAvailableforApplicant elements contains the string "Unavailable".
I have looked into Array.TrueforAll but not found a way to apply it to my situtation.
Apologies I don't think Im using the correct terminology which might make this slightly unclear.....
LINQ eats this sort of thing for breakfast:
applicantCounts.All(a => a.NadraDateAvailableforApplicant.Contains("Unavailable"))
We're using .All here to check if a condition is true for all elements of an enumerable.
Note you have a capitalization typo in the string search.
Using Array.TrueForAll would look like this:
bool all = Array.TrueForAll(
applicantCounts,
x => x.NadraDateAvailableforApplicant.Contains("Unavailable")
);
As for #Benjamin's approach, i would use IndexOf instead of Contains where you can specify a StringComparison in case you'd like a case insensitive search and or specify CultureInfo:
applicantCounts.All(app => app.NadraDateAvailableforApplicant.IndexOf("Unavailable", StringComparison.OrdinalIgnoreCase) >= 0);
Using fluent assertions, I would like to assert that a given string contains either one of two strings:
actual.Should().Contain("oneWay").Or().Should().Contain("anotherWay");
// eiter value should pass the assertion.
// for example: "you may do it oneWay." should pass, but
// "you may do it thisWay." should not pass
Only if neither of the values is contained, the assertion should fail. This does NOT work (not even compile) as there is no Or() operator.
This is how I do it now:
bool isVariant1 = actual.Contains(#"oneWay");
bool isVariant2 = actual.Contains(#"anotherWay");
bool anyVariant = (isVariant1 || isVariant2);
anyVariant.Should().BeTrue("because blahblah. Actual content was: " + actual);
This is verbose, and the "because" argument must get created manually to have a meaningful output.
Is there a way to do this in a more readable manner? A solution should also apply to other fluent assertion types, like Be(), HaveCount() etc...
I am using FluentAssertions version 2.2.0.0 on .NET 3.5, if that matters.
I would make it an extension to the string assertions. Something like this:
public static void BeAnyOf(this StringAssertions assertions, string[] expectations, string because, params string[] args) {
Execute.Assertion
.ForCondition(expectations.Any(assertions.Subject.Contains))
.BecauseOf(because, args)
.FailWith("Expected {context:string} to be any of {0}{reason}", expectations);
}
You could even fork the repository and provide me with a Pull Request to make it part of the next version.
Should not this work?
actual.Should().BeOneOf("oneWay", "anotherWay");
Worked for me using v3.1.229.
You could make it a little more readable by writing a simple string extension:
public static class StringExt
{
public static bool ContainsAnyOf(this string self, params string[] strings)
{
return strings.Any(self.Contains);
}
}
Then you could do this:
actual.ContainsAnyOf("oneWay", "anotherWay").Should().BeTrue("because of this reason");
Unfortunately this doesn't help with the "reason" part of the message, but I think it's a little better.
I'm using a List of platforms. I need to do something like platforms.get(i).X
I found something like that, it's called elementAt, but it only allows you to do platforms.elementAt(i).draw(). How do I check the variables of a specific object in the list?
You can access list elements with array index notation.
int x = platforms[i].X;
You could use a delegate for something like yourlist.Exists
if (stringlist.Exists(
delegate(String s)
{
return (s == "what you want to be found"); //this returns true if it is found.
}
))
{
//What you want to do if it is found.
}
Lookup more info about using lists and delegates and you should stumble on a way you could use this to solve your problem.
I have a string List<string> this would apply to all Lists. I needed to get the first item in a string list and then convert what I got back to a string.
Here is the working code using linq:
public List<string> AppGroup = new List<string>();
var group = SearchParameters.AppGroup.Take(1);
string firstAppGroup = String.Join(",", group.ToArray());
My question would be; Is this the best method to do what I am going for? Is there a better or shorter way to write this out? A good example of considering performance would be appreciated. If what I have is fine and no changes are needed, please let me know.
I am using framework 3.5 and above.
Your current means of grabbing the first item in the list is somewhat long-winded, and stems from the fact that using Take(1) returns an IEnumerable rather than the item in question.
Assuming SearchParameters.AppGroup is List<string>
string firstAppGroup =
SearchParameters.AppGroup.FirstOrDefault(); //returns null on empty set
is a much briefer way of stating the same intent.
EDIT:
As #CodeInChaos states, if you don't want to deal with a null value, use the null-coalescing operator to substitute an empty string in the case that null is returned:
string firstAppGroup =
SearchParameters.AppGroup.FirstOrDefault() ?? string.Empty;
Could be a one liner:
string firstAppGroup = String.Join(",", SearchParameters.AppGroup.First());